file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/43114/0xECD72d039362fbFC52F8A8724E720753c50aa3B1/sources/contracts/synapse/wrappers/NerveMetaBridgeZap.sol
swap deposit into bridge, gets nUSD
function swapAndRedeem( address to, uint256 chainId, IERC20 token, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external { IMetaSwapDeposit metaSwap = IMetaSwapDeposit(metaSwapMap[address(token)]); require(address(metaSwap) != address(0), "Metaswap is 0x00"); IERC20[] memory metaTokens = metaSwapTokensMap[address(metaSwap)]; metaTokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 swappedAmount = metaSwap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); if ( token.allowance(address(this), address(synapseBridge)) < swappedAmount ) { token.safeApprove(address(synapseBridge), MAX_UINT256); } synapseBridge.redeem(to, chainId, token, swappedAmount); }
4,588,879
[ 1, 22270, 443, 1724, 1368, 10105, 16, 5571, 290, 3378, 40, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7720, 1876, 426, 24903, 12, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 2687, 548, 16, 203, 565, 467, 654, 39, 3462, 1147, 16, 203, 565, 2254, 28, 1147, 1016, 1265, 16, 203, 565, 2254, 28, 1147, 1016, 774, 16, 203, 565, 2254, 5034, 6633, 16, 203, 565, 2254, 5034, 1131, 40, 93, 16, 203, 565, 2254, 5034, 14096, 203, 225, 262, 3903, 288, 203, 565, 467, 2781, 12521, 758, 1724, 2191, 12521, 273, 467, 2781, 12521, 758, 1724, 12, 3901, 12521, 863, 63, 2867, 12, 2316, 13, 19226, 203, 565, 2583, 12, 2867, 12, 3901, 12521, 13, 480, 1758, 12, 20, 3631, 315, 30853, 91, 438, 353, 374, 92, 713, 8863, 203, 565, 467, 654, 39, 3462, 8526, 3778, 2191, 5157, 225, 273, 2191, 12521, 5157, 863, 63, 2867, 12, 3901, 12521, 13, 15533, 203, 565, 2191, 5157, 63, 2316, 1016, 1265, 8009, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 6633, 1769, 203, 203, 565, 2254, 5034, 7720, 1845, 6275, 273, 2191, 12521, 18, 22270, 12, 203, 1377, 1147, 1016, 1265, 16, 203, 1377, 1147, 1016, 774, 16, 203, 1377, 6633, 16, 203, 1377, 1131, 40, 93, 16, 203, 1377, 14096, 203, 565, 11272, 203, 565, 309, 261, 203, 1377, 1147, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 1758, 12, 11982, 28933, 13691, 3719, 411, 7720, 1845, 6275, 203, 565, 262, 288, 203, 1377, 1147, 18, 4626, 12053, 537, 12, 2867, 12, 11982, 28933, 13691, 3631, 4552, 67, 57, 3217, 5034, 1769, 203, 565, 2 ]
./full_match/80001/0x73f2BD68540Dfb65db040D0Ecb3AfDEA552dA121/sources/node_modules/_sygnum/solidity-base-contracts/contracts/role/base/Operatorable.sol
* @dev The function should be called from new operators contract by admin to ensure that operatorsPending address is the real contract address./
function confirmOperatorsContract() public { if (operatorsPending == address(0)) revert OperatorableNewOperatorsZeroAddress(); if (msg.sender != operatorsPending) revert OperatorableCallerNotOperatorsContract(msg.sender); _setOperatorsContract(operatorsPending); }
5,563,256
[ 1, 1986, 445, 1410, 506, 2566, 628, 394, 12213, 6835, 635, 3981, 358, 3387, 716, 12213, 8579, 1758, 4202, 353, 326, 2863, 6835, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 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, 6932, 24473, 8924, 1435, 1071, 288, 203, 3639, 309, 261, 30659, 8579, 422, 1758, 12, 20, 3719, 15226, 11097, 429, 1908, 24473, 7170, 1887, 5621, 203, 203, 3639, 309, 261, 3576, 18, 15330, 480, 12213, 8579, 13, 15226, 11097, 429, 11095, 1248, 24473, 8924, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 389, 542, 24473, 8924, 12, 30659, 8579, 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 ]
./full_match/80001/0x01C6e9E22EEE9AbeF520c732D72f05E3ED9E44e5/sources/contracts/libraries/AkkaLibrary.sol
performs chained getAmountOut calculations on any number of pairs require(path.length >= 2, 'PancakeLibrary: INVALID_PATH');
function getAmountsOut( uint256 amountIn, address[][] memory path, uint256[][] memory fees ) internal view returns (uint256[] memory amounts) { amounts = new uint256[](path.length + 1); amounts[0] = amountIn; for (uint256 i; i < path.length; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves( path[i][0], path[i][1], path[i][2] ); amounts[i + 1] = getAmountOut( amounts[i], reserveIn, reserveOut, fees[i][0], fees[i][1], fees[i][2] ); } }
5,615,718
[ 1, 457, 9741, 20269, 24418, 1182, 20882, 603, 1281, 1300, 434, 5574, 2583, 12, 803, 18, 2469, 1545, 576, 16, 296, 4069, 23780, 9313, 30, 10071, 67, 4211, 8284, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24418, 87, 1182, 12, 203, 3639, 2254, 5034, 3844, 382, 16, 203, 3639, 1758, 63, 6362, 65, 3778, 589, 16, 203, 3639, 2254, 5034, 63, 6362, 65, 3778, 1656, 281, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 8526, 3778, 30980, 13, 288, 203, 3639, 30980, 273, 394, 2254, 5034, 8526, 12, 803, 18, 2469, 397, 404, 1769, 203, 3639, 30980, 63, 20, 65, 273, 3844, 382, 31, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 589, 18, 2469, 31, 277, 27245, 288, 203, 5411, 261, 11890, 5034, 20501, 382, 16, 2254, 5034, 20501, 1182, 13, 273, 31792, 264, 3324, 12, 203, 7734, 589, 63, 77, 6362, 20, 6487, 203, 7734, 589, 63, 77, 6362, 21, 6487, 203, 7734, 589, 63, 77, 6362, 22, 65, 203, 5411, 11272, 203, 5411, 30980, 63, 77, 397, 404, 65, 273, 24418, 1182, 12, 203, 7734, 30980, 63, 77, 6487, 203, 7734, 20501, 382, 16, 203, 7734, 20501, 1182, 16, 203, 7734, 1656, 281, 63, 77, 6362, 20, 6487, 203, 7734, 1656, 281, 63, 77, 6362, 21, 6487, 203, 7734, 1656, 281, 63, 77, 6362, 22, 65, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract PCKevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 PCPAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 PCPAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 PCPAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 PCPAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularKey is PCKevents {} contract PlayCoinKey is modularKey { using SafeMath for *; using NameFilter for string; using PCKKeysCalcLong for uint256; otherPCK private otherPCK_; PlayCoinGodInterface constant private PCGod = PlayCoinGodInterface(0x6f93Be8fD47EBb62F54ebd149B58658bf9BaCF4f); ProForwarderInterface constant private Pro_Inc = ProForwarderInterface(0x97354A7281693b7C93f6348Ba4eC38B9DDd76D6e); PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x47D1c777f1853cac97E6b81226B1F5108FBD7B81); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "PlayCoin Key"; string constant public symbol = "PCK"; uint256 private rndExtra_ = 15 minutes; // length of the very first ICO uint256 private rndGap_ = 15 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 12 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 6 hours; // max length a round timer can be uint256 constant private rndMin_ = 10 minutes; uint256 public rndReduceThreshold_ = 10e18; // 10ETH,reduce bool public closed_ = false; // admin is publish contract address private admin = msg.sender; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => PCKdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => PCKdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => PCKdatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => PCKdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => PCKdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (PCK, PCP) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = PCKdatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = PCKdatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = PCKdatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = PCKdatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (PCK, PCP) potSplit_[0] = PCKdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = PCKdatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = PCKdatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = PCKdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } modifier isRoundActivated() { require(round_[rID_].ended == false, "the round is finished"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; require(msg.sender == tx.origin, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } modifier onlyAdmins() { require(msg.sender == admin, "onlyAdmins failed - msg.sender is not an admin"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= function kill () onlyAdmins() public { require(round_[rID_].ended == true && closed_ == true, "the round is active or not close"); selfdestruct(admin); } function getRoundStatus() isActivated() public view returns(uint256, bool){ return (rID_, round_[rID_].ended); } function setThreshold(uint256 _threshold) onlyAdmins() public returns(uint256) { rndReduceThreshold_ = _threshold; return rndReduceThreshold_; } function setEnforce(bool _closed) onlyAdmins() public returns(bool) { closed_ = _closed; if( !closed_ && round_[rID_].ended == true && activated_ == true ){ nextRound(); } return closed_; } /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isRoundActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isRoundActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isRoundActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isRoundActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isRoundActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data PCKdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isRoundActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data PCKdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isRoundActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data PCKdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data PCKdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit PCKevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.PCPAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit PCKevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (!closed_ && _now > (round_[_rID].strt + rndGap_) && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if ( (closed_ || _now > round_[_rID].end ) && round_[_rID].ended == false ) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); if( !closed_ ){ nextRound(); } // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit PCKevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.PCPAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, PCKdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (!closed_ && _now > ( round_[_rID].strt + rndGap_ ) && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if ( ( closed_ || _now > round_[_rID].end ) && round_[_rID].ended == false ) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); if( !closed_ ) { nextRound(); } // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit PCKevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.PCPAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID, _eth); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(PCKdatasets.EventReturns memory _eventData_) private returns (PCKdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, PCKdatasets.EventReturns memory _eventData_) private returns (PCKdatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } function nextRound() private { rID_++; round_[rID_].strt = now; round_[rID_].end = now.add(rndInit_).add(rndGap_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(PCKdatasets.EventReturns memory _eventData_) private returns (PCKdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(Pro_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _p3d.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to PCGod if (_p3d > 0) PCGod.deposit.value(_p3d)(); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.PCPAmount = _p3d; _eventData_.newPot = _res; // start next round //rID_++; _rID++; round_[_rID].ended = false; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID, uint256 _eth) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time uint256 _newEndTime; if (_newTime < (rndMax_).add(_now)) _newEndTime = _newTime; else _newEndTime = rndMax_.add(_now); // biger to threshold, reduce if ( _eth >= rndReduceThreshold_ ) { _newEndTime = (_newEndTime).sub( (((_keys) / (1000000000000000000))).mul(rndInc_).add( (((_keys) / (2000000000000000000) ).mul(rndInc_)) ) ); // last add 10 minutes if( _newEndTime < _now + rndMin_ ) _newEndTime = _now + rndMin_ ; } round_[_rID].end = _newEndTime; } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) private returns(PCKdatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; if (!address(Pro_Inc).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // pay 1% out to FoMo3D short uint256 _long = _eth / 100; otherPCK_.potSwap.value(_long)(); // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit PCKevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to PCGod contract PCGod.deposit.value(_p3d)(); // set up event data _eventData_.PCPAmount = _p3d.add(_eventData_.PCPAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit PCKevents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, PCKdatasets.EventReturns memory _eventData_) private returns(PCKdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, PCKdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit PCKevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.PCPAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == admin, "only team just can activate" ); // make sure that its been linked. require(address(otherPCK_) != address(0), "must link to other PCK first"); // can only be ran once require(activated_ == false, "PCK already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherPCK(address _otherPCK) public { // only team just can activate require( msg.sender == admin, "only team just can activate" ); // make sure that it HASNT yet been linked. require(address(otherPCK_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap otherPCK_ = otherPCK(_otherPCK); } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library PCKdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 PCPAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library PCKKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherPCK { function potSwap() external payable; } interface PCKExtSettingInterface { function getFastGap() external view returns(uint256); function getLongGap() external view returns(uint256); function getFastExtra() external view returns(uint256); function getLongExtra() external view returns(uint256); } interface PlayCoinGodInterface { function deposit() external payable; } interface ProForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
* @dev withdraws all of your earnings. -functionhash- 0x3ccfd60b/ setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet set up our tx event data end the round (distributes pot) get their earnings gib moni build event data fire withdraw and distribute event in any other situation get their earnings gib moni fire withdraw event
function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { PCKdatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit PCKevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.PCPAmount, _eventData_.genAmount ); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit PCKevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } }
1,254,102
[ 1, 1918, 9446, 87, 777, 434, 3433, 425, 1303, 899, 18, 300, 915, 2816, 17, 374, 92, 23, 952, 8313, 4848, 70, 19, 3875, 1191, 436, 734, 11086, 813, 2158, 7291, 1599, 3875, 1906, 569, 364, 7291, 13750, 866, 358, 2621, 309, 3643, 711, 16926, 471, 1158, 1245, 711, 1086, 3643, 679, 4671, 444, 731, 3134, 2229, 871, 501, 679, 326, 3643, 261, 2251, 1141, 5974, 13, 336, 3675, 425, 1303, 899, 314, 495, 6921, 77, 1361, 871, 501, 4452, 598, 9446, 471, 25722, 871, 316, 1281, 1308, 20886, 336, 3675, 425, 1303, 899, 314, 495, 6921, 77, 4452, 598, 9446, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 1435, 203, 3639, 353, 28724, 1435, 203, 3639, 27803, 6925, 1435, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2254, 5034, 389, 86, 734, 273, 436, 734, 67, 31, 203, 540, 203, 3639, 2254, 5034, 389, 3338, 273, 2037, 31, 203, 540, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 3576, 18, 15330, 15533, 203, 540, 203, 3639, 2254, 5034, 389, 546, 31, 203, 540, 203, 3639, 309, 261, 67, 3338, 405, 3643, 67, 63, 67, 86, 734, 8009, 409, 597, 3643, 67, 63, 67, 86, 734, 8009, 3934, 422, 629, 597, 3643, 67, 63, 67, 86, 734, 8009, 1283, 86, 480, 374, 13, 203, 3639, 288, 203, 5411, 453, 3507, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 31, 203, 2398, 203, 5411, 3643, 67, 63, 67, 86, 734, 8009, 3934, 273, 638, 31, 203, 5411, 389, 2575, 751, 67, 273, 679, 11066, 24899, 2575, 751, 67, 1769, 203, 2398, 203, 5411, 389, 546, 273, 598, 9446, 41, 1303, 899, 24899, 84, 734, 1769, 203, 2398, 203, 5411, 309, 261, 67, 546, 405, 374, 13, 203, 7734, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 4793, 18, 13866, 24899, 546, 1769, 377, 203, 2398, 203, 5411, 389, 2575, 751, 27799, 15385, 751, 273, 389, 2575, 751, 27799, 15385, 751, 397, 261, 67, 3338, 380, 2130, 12648, 12648, 1769, 203, 5411, 389, 2575, 751, 27799, 15385, 5103, 273, 389, 2575, 751, 27799, 15385, 5103, 397, 389, 84, 734, 31, 203, 2398, 203, 2 ]
./full_match/1/0x2f51aE60379B661F3f02089FD5b3C9D8c9fB9D78/sources/localhost/v6/HCore.sol
returns sorted token addresses, used to handle return values from pairs sorted in this order
library UniswapV2Library { using SafeMath for uint; function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
3,106,528
[ 1, 6154, 3115, 1147, 6138, 16, 1399, 358, 1640, 327, 924, 628, 5574, 3115, 316, 333, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 1351, 291, 91, 438, 58, 22, 9313, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 445, 1524, 5157, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 16618, 1135, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 288, 203, 3639, 2583, 12, 2316, 37, 480, 1147, 38, 16, 296, 984, 291, 91, 438, 58, 22, 9313, 30, 19768, 10109, 67, 8355, 7031, 1090, 55, 8284, 203, 3639, 261, 2316, 20, 16, 1147, 21, 13, 273, 1147, 37, 411, 1147, 38, 692, 261, 2316, 37, 16, 1147, 38, 13, 294, 261, 2316, 38, 16, 1147, 37, 1769, 203, 3639, 2583, 12, 2316, 20, 480, 1758, 12, 20, 3631, 296, 984, 291, 91, 438, 58, 22, 9313, 30, 18449, 67, 15140, 8284, 203, 565, 289, 203, 203, 565, 445, 3082, 1290, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 1476, 1135, 261, 2867, 3082, 13, 288, 203, 3639, 261, 2867, 1147, 20, 16, 1758, 1147, 21, 13, 273, 1524, 5157, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 6848, 2934, 588, 4154, 12, 2316, 20, 16, 1147, 21, 1769, 203, 565, 289, 203, 203, 565, 445, 31792, 264, 3324, 12, 2867, 3272, 16, 1758, 1147, 37, 16, 1758, 1147, 38, 13, 2713, 1476, 1135, 261, 11890, 20501, 37, 16, 2254, 20501, 38, 13, 288, 203, 3639, 261, 2867, 1147, 20, 16, 13, 273, 1524, 5157, 12, 2316, 37, 16, 1147, 38, 1769, 2 ]
./full_match/137/0x45c98916d85e9325C9266e9BFad04629172baEF7/sources/project_/contracts/market/ERC721Listings.sol
* @dev See {IERC721Listings-listTokens}./
function listTokens(ListTokenInput[] calldata newListings) external { for (uint256 i = 0; i < newListings.length; i++) { address erc721Address = newListings[i].erc721Address; uint256 tokenId = newListings[i].tokenId; uint256 value = newListings[i].value; uint64 expireTimestamp = newListings[i].expireTimestamp; uint32 paymentTokenId = newListings[i].paymentTokenId; address tokenOwner = CollectionReader.tokenOwner( erc721Address, tokenId ); (bool isValid, string memory message) = _checkListAction( erc721Address, tokenId, value, expireTimestamp, paymentTokenId, tokenOwner ); if (isValid) { _listToken( erc721Address, tokenId, value, expireTimestamp, paymentTokenId, tokenOwner ); emit TokenListFailed( erc721Address, tokenId, message, _msgSender() ); } } }
4,752,265
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 682, 899, 17, 1098, 5157, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 666, 5157, 12, 682, 1345, 1210, 8526, 745, 892, 23605, 899, 13, 3903, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 23605, 899, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 6445, 71, 27, 5340, 1887, 273, 23605, 899, 63, 77, 8009, 12610, 27, 5340, 1887, 31, 203, 5411, 2254, 5034, 1147, 548, 273, 23605, 899, 63, 77, 8009, 2316, 548, 31, 203, 5411, 2254, 5034, 460, 273, 23605, 899, 63, 77, 8009, 1132, 31, 203, 5411, 2254, 1105, 6930, 4921, 273, 23605, 899, 63, 77, 8009, 14070, 4921, 31, 203, 5411, 2254, 1578, 5184, 1345, 548, 273, 23605, 899, 63, 77, 8009, 9261, 1345, 548, 31, 203, 5411, 1758, 1147, 5541, 273, 2200, 2514, 18, 2316, 5541, 12, 203, 7734, 6445, 71, 27, 5340, 1887, 16, 203, 7734, 1147, 548, 203, 5411, 11272, 203, 203, 5411, 261, 6430, 4908, 16, 533, 3778, 883, 13, 273, 389, 1893, 682, 1803, 12, 203, 7734, 6445, 71, 27, 5340, 1887, 16, 203, 7734, 1147, 548, 16, 203, 7734, 460, 16, 203, 7734, 6930, 4921, 16, 203, 7734, 5184, 1345, 548, 16, 203, 7734, 1147, 5541, 203, 5411, 11272, 203, 203, 5411, 309, 261, 26810, 13, 288, 203, 7734, 389, 1098, 1345, 12, 203, 10792, 6445, 71, 27, 5340, 1887, 16, 203, 10792, 1147, 548, 16, 203, 10792, 460, 16, 203, 10792, 6930, 4921, 16, 203, 10792, 5184, 1345, 548, 16, 203, 10792, 1147, 5541, 203, 7734, 11272, 203, 7734, 3626, 3155, 682, 2925, 12, 203, 10792, 6445, 71, 2 ]
pragma solidity ^0.4.20; //--------------------------------------------------------- // 增强版的代币合约 V 0.9 // WangYi 2018-05-07 //--------------------------------------------------------- contract ERC20ext { // stand function totalSupply() public constant returns (uint supply); function balanceOf( address who ) public constant returns (uint value); function allowance( address owner, address spender ) public constant returns (uint _allowance); function transfer( address to, uint value) public returns (bool ok); function transferFrom( address from, address to, uint value) public returns (bool ok); function approve( address spender, uint value ) public returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); // extand function postMessage(address dst, uint wad,string data) public returns (bool ok); function appointNewCFO(address newCFO) public returns (bool ok); function melt(address dst, uint256 wad) public returns (bool ok); function mint(address dst, uint256 wad) public returns (bool ok); function freeze(address dst, bool flag) public returns (bool ok); event MeltEvent(address indexed dst, uint256 wad); event MintEvent(address indexed dst, uint256 wad); event FreezeEvent(address indexed dst, bool flag); } //--------------------------------------------------------- // SafeMath 是一个安全数字运算的合约 //--------------------------------------------------------- contract SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } //--------------------------------------------------------- // sacToken 是一个增强版ERC20合约 //--------------------------------------------------------- contract sacToken is ERC20ext,SafeMath { string public name; string public symbol; uint8 public decimals = 18; address _cfo; uint256 _supply; //帐户的余额列表 mapping (address => uint256) _balances; //帐户的转账限额 mapping (address => mapping (address => uint256)) _allowance; //帐户的资金冻结 mapping (address => bool) public _frozen; //----------------------------------------------- // 初始化合约,并把所有代币都给CFO //----------------------------------------------- // @param initialSupply 发行总量 // @param tokenName 代币名称 // @param tokenSymbol 代币符号 //----------------------------------------------- function sacToken(uint256 initialSupply,string tokenName,string tokenSymbol) public { _cfo = msg.sender; _supply = initialSupply * 10 ** uint256(decimals); _balances[_cfo] = _supply; name = tokenName; symbol = tokenSymbol; } //----------------------------------------------- // 判断合约调用者是否 CFO //----------------------------------------------- modifier onlyCFO() { require(msg.sender == _cfo); _; } //----------------------------------------------- // 获取货币供应量 //----------------------------------------------- function totalSupply() public constant returns (uint256) { return _supply; } //----------------------------------------------- // 查询账户余额 //----------------------------------------------- // @param src 帐户地址 //----------------------------------------------- function balanceOf(address src) public constant returns (uint256) { return _balances[src]; } //----------------------------------------------- // 查询账户转账限额 //----------------------------------------------- // @param src 来源帐户地址 // @param dst 目标帐户地址 //----------------------------------------------- function allowance(address src, address dst) public constant returns (uint256) { return _allowance[src][dst]; } //----------------------------------------------- // 账户转账 //----------------------------------------------- // @param dst 目标帐户地址 // @param wad 转账金额 //----------------------------------------------- function transfer(address dst, uint wad) public returns (bool) { //检查冻结帐户 require(!_frozen[msg.sender]); require(!_frozen[dst]); //检查帐户余额 require(_balances[msg.sender] >= wad); _balances[msg.sender] = sub(_balances[msg.sender],wad); _balances[dst] = add(_balances[dst], wad); Transfer(msg.sender, dst, wad); return true; } //----------------------------------------------- // 账户转账带检查限额 //----------------------------------------------- // @param src 来源帐户地址 // @param dst 目标帐户地址 // @param wad 转账金额 //----------------------------------------------- function transferFrom(address src, address dst, uint wad) public returns (bool) { //检查冻结帐户 require(!_frozen[msg.sender]); require(!_frozen[dst]); //检查帐户余额 require(_balances[src] >= wad); //检查帐户限额 require(_allowance[src][msg.sender] >= wad); _allowance[src][msg.sender] = sub(_allowance[src][msg.sender],wad); _balances[src] = sub(_balances[src],wad); _balances[dst] = add(_balances[dst],wad); //转账事件 Transfer(src, dst, wad); return true; } //----------------------------------------------- // 设置转账限额 //----------------------------------------------- // @param dst 目标帐户地址 // @param wad 限制金额 //----------------------------------------------- function approve(address dst, uint256 wad) public returns (bool) { _allowance[msg.sender][dst] = wad; //设置事件 Approval(msg.sender, dst, wad); return true; } //----------------------------------------------- // 账户转账带附加数据 //----------------------------------------------- // @param dst 目标帐户地址 // @param wad 限制金额 // @param data 附加数据 //----------------------------------------------- function postMessage(address dst, uint wad,string data) public returns (bool) { return transfer(dst,wad); } //----------------------------------------------- // 任命新的CFO //----------------------------------------------- // @param newCFO 新的CFO帐户地址 //----------------------------------------------- function appointNewCFO(address newCFO) onlyCFO public returns (bool) { if (newCFO != _cfo) { _cfo = newCFO; return true; } else { return false; } } //----------------------------------------------- // 冻结帐户 //----------------------------------------------- // @param dst 目标帐户地址 // @param flag 冻结 //----------------------------------------------- function freeze(address dst, bool flag) onlyCFO public returns (bool) { _frozen[dst] = flag; //冻结帐户事件 FreezeEvent(dst, flag); return true; } //----------------------------------------------- // 铸造代币 //----------------------------------------------- // @param dst 目标帐户地址 // @param wad 铸造金额 //----------------------------------------------- function mint(address dst, uint256 wad) onlyCFO public returns (bool) { //目标帐户地址铸造代币,同时更新总量 _balances[dst] = add(_balances[dst],wad); _supply = add(_supply,wad); //铸造代币事件 MintEvent(dst, wad); return true; } //----------------------------------------------- // 销毁代币 //----------------------------------------------- // @param dst 目标帐户地址 // @param wad 销毁金额 //----------------------------------------------- function melt(address dst, uint256 wad) onlyCFO public returns (bool) { //检查帐户余额 require(_balances[dst] >= wad); //销毁目标帐户地址代币,同时更新总量 _balances[dst] = sub(_balances[dst],wad); _supply = sub(_supply,wad); //销毁代币事件 MeltEvent(dst, wad); return true; } }
* @dev Adds two numbers, throws on overflow./
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
107,960
[ 1, 3655, 2795, 5600, 16, 1216, 603, 9391, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 276, 13, 7010, 225, 288, 203, 565, 276, 273, 279, 397, 324, 31, 203, 565, 1815, 12, 71, 1545, 279, 1769, 203, 565, 327, 276, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; 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; } } // source : https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md contract ERC20 { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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 QuickxToken is ERC20 { using SafeMath for uint; // ------------------------------------------------------------------------ // EVENTS // ------------------------------------------------------------------------ event LogBurn(address indexed from, uint256 amount); event LogFreezed(address targetAddress, bool frozen); event LogEmerygencyFreezed(bool emergencyFreezeStatus); // ------------------------------------------------------------------------ // STATE VARIABLES // ------------------------------------------------------------------------ string public name = "QuickX Protocol"; string public symbol = "QCX"; uint8 public decimals = 8; address public owner; uint public totalSupply = 500000000 * (10 ** 8); uint public currentSupply = 250000000 * (10 ** 8); // 50% of total supply bool public emergencyFreeze = true; // ------------------------------------------------------------------------ // MAPPINNGS // ------------------------------------------------------------------------ mapping (address => uint) internal balances; mapping (address => mapping (address => uint) ) private allowed; mapping (address => bool) private frozen; // ------------------------------------------------------------------------ // CONSTRUCTOR // ------------------------------------------------------------------------ constructor () public { owner = address(0x2cf93Eed42d4D0C0121F99a4AbBF0d838A004F64); } // ------------------------------------------------------------------------ // MODIFIERS // ------------------------------------------------------------------------ modifier onlyOwner { require(msg.sender == owner); _; } modifier unfreezed(address _account) { require(!frozen[_account]); _; } modifier noEmergencyFreeze() { require(!emergencyFreeze); _; } // ------------------------------------------------------------------------ // Transfer Token // ------------------------------------------------------------------------ function transfer(address _to, uint _value) public unfreezed(_to) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { require(_to != 0x0); _transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Approve others to spend on your behalf // RACE CONDITION HANDLED // ------------------------------------------------------------------------ function approve(address _spender, uint _value) public unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() returns (bool success) { uint oldAllowance = allowed[msg.sender][_spender]; if (_subtractedValue > oldAllowance) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldAllowance.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Transferred approved amount from other's account // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint _value) public unfreezed(_to) unfreezed(_from) noEmergencyFreeze() returns (bool success) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } // ------------------------------------------------------------------------ // ONLYOWNER METHODS // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Freeze account - onlyOwner // ------------------------------------------------------------------------ function freezeAccount (address _target, bool _freeze) public onlyOwner { require(_target != 0x0); frozen[_target] = _freeze; emit LogFreezed(_target, _freeze); } // ------------------------------------------------------------------------ // Emerygency freeze - onlyOwner // ------------------------------------------------------------------------ function emergencyFreezeAllAccounts (bool _freeze) public onlyOwner { emergencyFreeze = _freeze; emit LogEmerygencyFreezed(_freeze); } // ------------------------------------------------------------------------ // Burn (Destroy tokens) // ------------------------------------------------------------------------ function burn(uint256 _value) public onlyOwner returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); currentSupply = currentSupply.sub(_value); emit LogBurn(msg.sender, _value); return true; } // ------------------------------------------------------------------------ // CONSTANT METHODS // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Check Balance : Constant // ------------------------------------------------------------------------ function balanceOf(address _tokenOwner) public view returns (uint) { return balances[_tokenOwner]; } // ------------------------------------------------------------------------ // Total supply : Constant // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return totalSupply; } // ------------------------------------------------------------------------ // Check Allowance : Constant // ------------------------------------------------------------------------ function allowance(address _tokenOwner, address _spender) public view returns (uint) { return allowed[_tokenOwner][_spender]; } // ------------------------------------------------------------------------ // Get Freeze Status : Constant // ------------------------------------------------------------------------ function isFreezed(address _targetAddress) public view returns (bool) { return frozen[_targetAddress]; } function _transfer(address from, address to, uint amount) internal { require(balances[from] >= amount); uint balBeforeTransfer = balances[from].add(balances[to]); balances[from] = balances[from].sub(amount); balances[to] = balances[to].add(amount); uint balAfterTransfer = balances[from].add(balances[to]); assert(balBeforeTransfer == balAfterTransfer); emit Transfer(from, to, amount); } } contract QuickxProtocol is QuickxToken { using SafeMath for uint; // ------------------------------------------------------------------------ // STATE VARIABLES 00000000 // ------------------------------------------------------------------------ // 50% of totail coins will be sold in ico uint public tokenSaleAllocation = 250000000 * (10 ** 8); // 2% of total supply goes for bounty uint public bountyAllocation = 10000000 * (10 ** 8); //13% of total tokens is reserved for founders and team uint public founderAllocation = 65000000 * (10 ** 8); //5% of total tokens is reserved for partners uint public partnersAllocation = 25000000 * (10 ** 8); // 15% of total tokens is for Liquidity reserve uint public liquidityReserveAllocation = 75000000 * (10 ** 8); //5% of total tokens is reserved for advisors uint public advisoryAllocation = 25000000 * (10 ** 8); //10% of total tokens in reserved for pre-seed Inverstors uint public preSeedInvestersAllocation = 50000000 * (10 ** 8); uint[] public founderFunds = [ 1300000000000000, 2600000000000000, 3900000000000000, 5200000000000000, 6500000000000000 ]; // 8 decimals included uint[] public advisoryFunds = [ 500000000000000, 1000000000000000, 1500000000000000, 2000000000000000, 2500000000000000 ]; uint public founderFundsWithdrawn = 0; uint public advisoryFundsWithdrawn = 0; // check allcatios bool public bountyAllocated; //bool public founderAllocated; bool public partnersAllocated; bool public liquidityReserveAllocated; bool public preSeedInvestersAllocated; uint public icoSuccessfulTime; bool public isIcoSuccessful; address public beneficiary; // address of hard wallet of admin. // ico state variables uint private totalRaised = 0; // total wei raised by ICO uint private totalCoinsSold = 0; // total coins sold in ICO uint private softCap; // soft cap target in ether uint private hardCap; // hard cap target in ether // rate is number of tokens (including decimals) per wei uint private rateNum; // rate numerator (to avoid fractions) (rate = rateNum/rateDeno) uint private rateDeno; // rate denominator (to avoid fractions) (rate = rateNum/rateDeno) uint public tokenSaleStart; // time when token sale starts uint public tokenSaleEnds; // time when token sale ends bool public icoPaused; // ICO can be paused anytime // ------------------------------------------------------------------------ // EVENTS // ------------------------------------------------------------------------ event LogBontyAllocated( address recepient, uint amount); event LogPartnersAllocated( address recepient, uint amount); event LogLiquidityreserveAllocated( address recepient, uint amount); event LogPreSeedInverstorsAllocated( address recepient, uint amount); event LogAdvisorsAllocated( address recepient, uint amount); event LogFoundersAllocated( address indexed recepient, uint indexed amount); // ico events event LogFundingReceived( address indexed addr, uint indexed weiRecieved, uint indexed tokenTransferred, uint currentTotal); event LogRateUpdated( uint rateNum, uint rateDeno); event LogPaidToOwner( address indexed beneficiary, uint indexed amountPaid); event LogWithdrawnRemaining( address _owner, uint amountWithdrawan); event LogIcoEndDateUpdated( uint _oldEndDate, uint _newEndDate); event LogIcoSuccessful(); /* mappings */ mapping (address => uint) public contributedAmount; // amount contributed by a user // ------------------------------------------------------------------------ // CONSTRUCTOR // ------------------------------------------------------------------------ constructor () public { owner = address(0x2cf93Eed42d4D0C0121F99a4AbBF0d838A004F64); rateNum = 75; rateDeno = 100000000; softCap = 4000 ether; hardCap = 30005019135500000000000 wei; tokenSaleStart = now; tokenSaleEnds = now; balances[this] = currentSupply; isIcoSuccessful = true; icoSuccessfulTime = now; beneficiary = address(0x2cf93Eed42d4D0C0121F99a4AbBF0d838A004F64); emit LogIcoSuccessful(); emit Transfer(0x0, address(this), currentSupply); } /* Fallback function */ function () public payable { require(msg.data.length == 0); contribute(); } modifier isFundRaising() { require( totalRaised <= hardCap && now >= tokenSaleStart && now < tokenSaleEnds && !icoPaused ); _; } // ------------------------------------------------------------------------ // ONLY OWNER METHODS // ------------------------------------------------------------------------ function allocateBountyTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!bountyAllocated); balances[owner] = balances[owner].add(bountyAllocation); currentSupply = currentSupply.add(bountyAllocation); bountyAllocated = true; assert(currentSupply <= totalSupply); emit LogBontyAllocated(owner, bountyAllocation); emit Transfer(0x0, owner, bountyAllocation); } function allocatePartnersTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!partnersAllocated); balances[owner] = balances[owner].add(partnersAllocation); currentSupply = currentSupply.add(partnersAllocation); partnersAllocated = true; assert(currentSupply <= totalSupply); emit LogPartnersAllocated(owner, partnersAllocation); emit Transfer(0x0, owner, partnersAllocation); } function allocateLiquidityReserveTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!liquidityReserveAllocated); balances[owner] = balances[owner].add(liquidityReserveAllocation); currentSupply = currentSupply.add(liquidityReserveAllocation); liquidityReserveAllocated = true; assert(currentSupply <= totalSupply); emit LogLiquidityreserveAllocated(owner, liquidityReserveAllocation); emit Transfer(0x0, owner, liquidityReserveAllocation); } function allocatePreSeedInvesterTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); require(!preSeedInvestersAllocated); balances[owner] = balances[owner].add(preSeedInvestersAllocation); currentSupply = currentSupply.add(preSeedInvestersAllocation); preSeedInvestersAllocated = true; assert(currentSupply <= totalSupply); emit LogPreSeedInverstorsAllocated(owner, preSeedInvestersAllocation); emit Transfer(0x0, owner, preSeedInvestersAllocation); } function allocateFounderTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); uint calculatedFunds = calculateFoundersTokens(); uint eligibleFunds = calculatedFunds.sub(founderFundsWithdrawn); require(eligibleFunds > 0); balances[owner] = balances[owner].add(eligibleFunds); currentSupply = currentSupply.add(eligibleFunds); founderFundsWithdrawn = founderFundsWithdrawn.add(eligibleFunds); assert(currentSupply <= totalSupply); emit LogFoundersAllocated(owner, eligibleFunds); emit Transfer(0x0, owner, eligibleFunds); } function allocateAdvisoryTokens() public onlyOwner { require(isIcoSuccessful && icoSuccessfulTime > 0); uint calculatedFunds = calculateAdvisoryTokens(); uint eligibleFunds = calculatedFunds.sub(advisoryFundsWithdrawn); require(eligibleFunds > 0); balances[owner] = balances[owner].add(eligibleFunds); currentSupply = currentSupply.add(eligibleFunds); advisoryFundsWithdrawn = advisoryFundsWithdrawn.add(eligibleFunds); assert(currentSupply <= totalSupply); emit LogAdvisorsAllocated(owner, eligibleFunds); emit Transfer(0x0, owner, eligibleFunds); } // there is no explicit need of this function as funds are directly transferred to owner's hardware wallet. // but this is kept just to avoid any case when ETH is locked in contract function withdrawEth () public onlyOwner { owner.transfer(address(this).balance); emit LogPaidToOwner(owner, address(this).balance); } function updateRate (uint _rateNum, uint _rateDeno) public onlyOwner { rateNum = _rateNum; rateDeno = _rateDeno; emit LogRateUpdated(rateNum, rateDeno); } function updateIcoEndDate(uint _newDate) public onlyOwner { uint oldEndDate = tokenSaleEnds; tokenSaleEnds = _newDate; emit LogIcoEndDateUpdated (oldEndDate, _newDate); } // admin can withdraw token not sold in ICO function withdrawUnsold() public onlyOwner returns (bool) { require(now > tokenSaleEnds); uint unsold = (tokenSaleAllocation.sub(totalCoinsSold)); balances[owner] = balances[owner].add(unsold); balances[address(this)] = balances[address(this)].sub(unsold); emit LogWithdrawnRemaining(owner, unsold); emit Transfer(address(this), owner, unsold); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address _tokenAddress, uint _value) public onlyOwner returns (bool success) { // this condition is to stop admin from withdrawing funds unless all funds of ICO are successfully settelled if (_tokenAddress == address(this)) { require(now > tokenSaleStart + 730 days); // expecting 2 years time, all vested funds will be released. } return ERC20(_tokenAddress).transfer(owner, _value); } function pauseICO(bool pauseStatus) public onlyOwner returns (bool status) { require(icoPaused != pauseStatus); icoPaused = pauseStatus; return true; } // ------------------------------------------------------------------------ // PUBLIC METHODS // ------------------------------------------------------------------------ function contribute () public payable isFundRaising returns(bool) { uint calculatedTokens = calculateTokens(msg.value); require(calculatedTokens > 0); require(totalCoinsSold.add(calculatedTokens) <= tokenSaleAllocation); contributedAmount[msg.sender] = contributedAmount[msg.sender].add(msg.value); totalRaised = totalRaised.add(msg.value); totalCoinsSold = totalCoinsSold.add(calculatedTokens); _transfer(address(this), msg.sender, calculatedTokens); beneficiary.transfer(msg.value); checkIfSoftCapReached(); emit LogFundingReceived(msg.sender, msg.value, calculatedTokens, totalRaised); emit LogPaidToOwner(beneficiary, msg.value); return true; } // ------------------------------------------------------------------------ // CONSTANT METHODS // ------------------------------------------------------------------------ function calculateTokens(uint weisToTransfer) public view returns(uint) { uint discount = calculateDiscount(); uint coins = weisToTransfer.mul(rateNum).mul(discount).div(100 * rateDeno); return coins; } function getTotalWeiRaised () public view returns(uint totalEthRaised) { return totalRaised; } function getTotalCoinsSold() public view returns(uint _coinsSold) { return totalCoinsSold; } function getSoftCap () public view returns(uint _softCap) { return softCap; } function getHardCap () public view returns(uint _hardCap) { return hardCap; } function getContractOwner () public view returns(address contractOwner) { return owner; } function isContractAcceptingPayment() public view returns (bool) { if (totalRaised < hardCap && now >= tokenSaleStart && now < tokenSaleEnds && totalCoinsSold < tokenSaleAllocation) return true; else return false; } // ------------------------------------------------------------------------ // INTERNAL METHODS // ------------------------------------------------------------------------ function calculateFoundersTokens() internal view returns(uint) { uint timeAferIcoSuceess = now.sub(icoSuccessfulTime); uint timeSpendInMonths = timeAferIcoSuceess.div(30 days); if (timeSpendInMonths >= 3 && timeSpendInMonths < 6) { return founderFunds[0]; } else if (timeSpendInMonths >= 6 && timeSpendInMonths < 9) { return founderFunds[1]; } else if (timeSpendInMonths >= 9 && timeSpendInMonths < 12) { return founderFunds[2]; } else if (timeSpendInMonths >= 12 && timeSpendInMonths < 18) { return founderFunds[3]; } else if (timeSpendInMonths >= 18) { return founderFunds[4]; } else { revert(); } } function calculateAdvisoryTokens()internal view returns(uint) { uint timeSpentAfterIcoEnd = now.sub(icoSuccessfulTime); uint timeSpendInMonths = timeSpentAfterIcoEnd.div(30 days); if (timeSpendInMonths >= 0 && timeSpendInMonths < 3) return advisoryFunds[0]; if (timeSpendInMonths < 6) return advisoryFunds[1]; if (timeSpendInMonths < 9) return advisoryFunds[2]; if (timeSpendInMonths < 12) return advisoryFunds[3]; if (timeSpendInMonths >= 12) return advisoryFunds[4]; revert(); } function checkIfSoftCapReached() internal returns (bool) { if (totalRaised >= softCap && !isIcoSuccessful) { isIcoSuccessful = true; icoSuccessfulTime = now; emit LogIcoSuccessful(); } return; } function calculateDiscount() internal view returns(uint) { if (totalCoinsSold < 12500000000000000) { return 115; // 15 % discount } else if (totalCoinsSold < 18750000000000000) { return 110; // 10 % discount } else if (totalCoinsSold < 25000000000000000) { return 105; // 5 % discount } else { // this case should never arise return 100; // 0 % discount } } }
total coins sold in ICO
uint private totalCoinsSold = 0;
15,882,499
[ 1, 4963, 276, 9896, 272, 1673, 316, 467, 3865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 2078, 39, 9896, 55, 1673, 273, 374, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x5Fc847Ab7e97787808c772571f496F9F4ac0B346/sources/contracts/Crowdfunding.sol
Get the corresponding campaign by id
function getDonators(uint256 _campaignId) view public returns (address[] memory, uint256[] memory) { Campaign storage campaign = campaigns[_campaignId]; return (campaign.donators, campaign.donations); }
11,628,690
[ 1, 967, 326, 4656, 8965, 635, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 265, 3062, 12, 11890, 5034, 389, 14608, 548, 13, 1476, 1071, 1135, 261, 2867, 8526, 3778, 16, 2254, 5034, 8526, 3778, 13, 288, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 67, 14608, 548, 15533, 203, 540, 203, 3639, 327, 261, 14608, 18, 19752, 3062, 16, 8965, 18, 19752, 1012, 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 ]
//SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {INonfungiblePositionManager} from "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import {IWETH9} from "../interfaces/IWETH9.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; import {IShortPowerPerp} from "../interfaces/IShortPowerPerp.sol"; import {IOracle} from "../interfaces/IOracle.sol"; import {VaultLib} from "../libs/VaultLib.sol"; import {Uint256Casting} from "../libs/Uint256Casting.sol"; import {Power2Base} from "../libs/Power2Base.sol"; /** * * Error * C0: Paused * C1: Not paused * C2: Shutdown * C3: Not shutdown * C4: Invalid oracle address * C5: Invalid shortPowerPerp address * C6: Invalid wPowerPerp address * C7: Invalid weth address * C8: Invalid quote currency address * C9: Invalid eth:quoteCurrency pool address * C10: Invalid wPowerPerp:eth pool address * C11: Invalid Uniswap position manager * C12: Can not liquidate safe vault * C13: Invalid address * C14: Set fee recipient first * C15: Fee too high * C16: Paused too many times * C17: Pause time limit exceeded * C18: Not enough paused time has passed * C19: Cannot receive eth * C20: Invalid vault id * C21: Need full liquidation * C22: Dust vault left * C23: Invalid nft * C24: Invalid state * C25: Not allowed */ contract Controller is Ownable, ReentrancyGuard { using SafeMath for uint256; using Uint256Casting for uint256; using VaultLib for VaultLib.Vault; using Address for address payable; uint256 internal constant MIN_COLLATERAL = 0.5 ether; /// @dev system can only be paused for 182 days from deployment uint256 internal constant PAUSE_TIME_LIMIT = 182 days; uint256 internal constant FUNDING_PERIOD = 1 days; uint32 public constant TWAP_PERIOD = 5 minutes; //80% of index uint256 internal constant LOWER_MARK_RATIO = 8e17; //125% of index uint256 internal constant UPPER_MARK_RATIO = 125e16; // 10% uint256 internal constant LIQUIDATION_BOUNTY = 1e17; // 2% uint256 internal constant REDUCE_DEBT_BOUNTY = 2e16; /// @dev basic unit used for calculation uint256 private constant ONE = 1e18; uint256 private constant ONE_ONE = 1e36; address public immutable weth; address public immutable quoteCurrency; address public immutable ethQuoteCurrencyPool; /// @dev address of the powerPerp/weth pool address public immutable wPowerPerpPool; address internal immutable uniswapPositionManager; address public immutable shortPowerPerp; address public immutable wPowerPerp; address public immutable oracle; address public feeRecipient; uint256 internal immutable deployTimestamp; /// @dev fee rate in basis point. feeRate of 1 = 0.01% uint256 public feeRate; /// @dev the settlement price for each wPowerPerp for settlement uint256 public indexForSettlement; uint256 public pausesLeft = 4; uint256 public lastPauseTime; // these 2 parameters are always updated together. Use uint128 to batch read and write. uint128 public normalizationFactor; uint128 public lastFundingUpdateTimestamp; bool internal immutable isWethToken0; bool public isShutDown; bool public isSystemPaused; /// @dev vault data storage mapping(uint256 => VaultLib.Vault) public vaults; /// Events event OpenVault(address sender, uint256 vaultId); event DepositCollateral(address sender, uint256 vaultId, uint256 amount); event DepositUniPositionToken(address sender, uint256 vaultId, uint256 tokenId); event WithdrawCollateral(address sender, uint256 vaultId, uint256 amount); event WithdrawUniPositionToken(address sender, uint256 vaultId, uint256 tokenId); event MintShort(address sender, uint256 amount, uint256 vaultId); event BurnShort(address sender, uint256 amount, uint256 vaultId); event ReduceDebt( address sender, uint256 vaultId, uint256 ethRedeemed, uint256 wPowerPerpRedeemed, uint256 wPowerPerpBurned, uint256 wPowerPerpExcess, uint256 bounty ); event UpdateOperator(address sender, uint256 vaultId, address operator); event FeeRateUpdated(uint256 oldFee, uint256 newFee); event FeeRecipientUpdated(address oldFeeRecipient, address newFeeRecipient); event Liquidate(address liquidator, uint256 vaultId, uint256 debtAmount, uint256 collateralPaid); event NormalizationFactorUpdated( uint256 oldNormFactor, uint256 newNormFactor, uint256 lastModificationTimestamp, uint256 timestamp ); event Paused(uint256 pausesLeft); event UnPaused(address unpauser); event Shutdown(uint256 indexForSettlement); event RedeemLong(address sender, uint256 wPowerPerpAmount, uint256 payoutAmount); event RedeemShort(address sender, uint256 vauldId, uint256 collateralAmount); modifier notPaused() { require(!isSystemPaused, "C0"); _; } modifier isPaused() { require(isSystemPaused, "C1"); _; } modifier notShutdown() { require(!isShutDown, "C2"); _; } modifier isShutdown() { require(isShutDown, "C3"); _; } /** * @notice constructor * @param _oracle oracle address * @param _shortPowerPerp ERC721 token address representing the short position * @param _wPowerPerp ERC20 token address representing the long position * @param _weth weth address * @param _quoteCurrency quoteCurrency address * @param _ethQuoteCurrencyPool uniswap v3 pool for weth / quoteCurrency * @param _wPowerPerpPool uniswap v3 pool for wPowerPerp / weth * @param _uniPositionManager uniswap v3 position manager address */ constructor( address _oracle, address _shortPowerPerp, address _wPowerPerp, address _weth, address _quoteCurrency, address _ethQuoteCurrencyPool, address _wPowerPerpPool, address _uniPositionManager ) { require(_oracle != address(0), "C4"); require(_shortPowerPerp != address(0), "C5"); require(_wPowerPerp != address(0), "C6"); require(_weth != address(0), "C7"); require(_quoteCurrency != address(0), "C8"); require(_ethQuoteCurrencyPool != address(0), "C9"); require(_wPowerPerpPool != address(0), "C10"); require(_uniPositionManager != address(0), "C11"); oracle = _oracle; shortPowerPerp = _shortPowerPerp; wPowerPerp = _wPowerPerp; weth = _weth; quoteCurrency = _quoteCurrency; ethQuoteCurrencyPool = _ethQuoteCurrencyPool; wPowerPerpPool = _wPowerPerpPool; uniswapPositionManager = _uniPositionManager; isWethToken0 = _weth < _wPowerPerp; normalizationFactor = 1e18; deployTimestamp = block.timestamp; lastFundingUpdateTimestamp = block.timestamp.toUint128(); } /** * ====================== * | External Functions | * ====================== */ /** * @notice returns the expected normalization factor, if the funding is paid right now * @dev can be used for on-chain and off-chain calculations */ function getExpectedNormalizationFactor() external view returns (uint256) { return _getNewNormalizationFactor(); } /** * @notice get the index price of the powerPerp, scaled down * @dev the index price is scaled down by INDEX_SCALE in the associated PowerXBase library * @dev this is the index price used when calculating funding and for collateralization * @param _period period which you want to calculate twap with * @return index price denominated in $USD, scaled by 1e18 */ function getIndex(uint32 _period) external view returns (uint256) { return Power2Base._getIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); } /** * @notice the unscaled index of the power perp in USD, scaled by 18 decimals * @dev this is the mark that would be be used for future funding after a new normalization factor is applied * @param _period period which you want to calculate twap with * @return index price denominated in $USD, scaled by 1e18 */ function getUnscaledIndex(uint32 _period) external view returns (uint256) { return Power2Base._getUnscaledIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); } /** * @notice get the expected mark price of powerPerp after funding has been applied * @param _period period of time for the twap in seconds * @return mark price denominated in $USD, scaled by 1e18 */ function getDenormalizedMark(uint32 _period) external view returns (uint256) { return Power2Base._getDenormalizedMark( _period, oracle, wPowerPerpPool, ethQuoteCurrencyPool, weth, quoteCurrency, wPowerPerp, _getNewNormalizationFactor() ); } /** * @notice get the mark price of powerPerp before funding has been applied * @dev this is the mark that would be used to calculate a new normalization factor if funding was calculated now * @param _period period which you want to calculate twap with * @return mark price denominated in $USD, scaled by 1e18 */ function getDenormalizedMarkForFunding(uint32 _period) external view returns (uint256) { return Power2Base._getDenormalizedMark( _period, oracle, wPowerPerpPool, ethQuoteCurrencyPool, weth, quoteCurrency, wPowerPerp, normalizationFactor ); } /** * @dev return if the vault is properly collateralized * @param _vaultId id of the vault * @return true if the vault is properly collateralized */ function isVaultSafe(uint256 _vaultId) external view returns (bool) { VaultLib.Vault memory vault = vaults[_vaultId]; uint256 expectedNormalizationFactor = _getNewNormalizationFactor(); return _isVaultSafe(vault, expectedNormalizationFactor); } /** * @notice deposit collateral and mint wPowerPerp (non-rebasing) for specified powerPerp (rebasing) amount * @param _vaultId vault to mint wPowerPerp in * @param _powerPerpAmount amount of powerPerp to mint * @param _uniTokenId uniswap v3 position token id (additional collateral) * @return vaultId * @return amount of wPowerPerp minted */ function mintPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _uniTokenId ) external payable notPaused nonReentrant returns (uint256, uint256) { return _openDepositMint(msg.sender, _vaultId, _powerPerpAmount, msg.value, _uniTokenId, false); } /** * @notice deposit collateral and mint wPowerPerp * @param _vaultId vault to mint wPowerPerp in * @param _wPowerPerpAmount amount of wPowerPerp to mint * @param _uniTokenId uniswap v3 position token id (additional collateral) * @return vaultId */ function mintWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _uniTokenId ) external payable notPaused nonReentrant returns (uint256) { (uint256 vaultId, ) = _openDepositMint(msg.sender, _vaultId, _wPowerPerpAmount, msg.value, _uniTokenId, true); return vaultId; } /** * @dev deposit collateral into a vault * @param _vaultId id of the vault */ function deposit(uint256 _vaultId) external payable notPaused nonReentrant { _checkVaultId(_vaultId); _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _addEthCollateral(cachedVault, _vaultId, msg.value); _writeVault(_vaultId, cachedVault); } /** * @notice deposit uniswap position token into a vault to increase collateral ratio * @param _vaultId id of the vault * @param _uniTokenId uniswap position token id */ function depositUniPositionToken(uint256 _vaultId, uint256 _uniTokenId) external notPaused nonReentrant { _checkVaultId(_vaultId); _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _depositUniPositionToken(cachedVault, msg.sender, _vaultId, _uniTokenId); _writeVault(_vaultId, cachedVault); } /** * @notice withdraw collateral from a vault * @param _vaultId id of the vault * @param _amount amount of eth to withdraw */ function withdraw(uint256 _vaultId, uint256 _amount) external notPaused nonReentrant { uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _withdrawCollateral(cachedVault, msg.sender, _vaultId, _amount); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); payable(msg.sender).sendValue(_amount); } /** * @notice withdraw uniswap v3 position token from a vault * @param _vaultId id of the vault */ function withdrawUniPositionToken(uint256 _vaultId) external notPaused nonReentrant { uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _withdrawUniPositionToken(cachedVault, msg.sender, _vaultId); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); } /** * @notice burn wPowerPerp and remove collateral from a vault * @param _vaultId id of the vault * @param _wPowerPerpAmount amount of wPowerPerp to burn * @param _withdrawAmount amount of eth to withdraw */ function burnWPowerPerpAmount( uint256 _vaultId, uint256 _wPowerPerpAmount, uint256 _withdrawAmount ) external notPaused nonReentrant { _burnAndWithdraw(msg.sender, _vaultId, _wPowerPerpAmount, _withdrawAmount, true); } /** * @notice burn powerPerp and remove collateral from a vault * @param _vaultId id of the vault * @param _powerPerpAmount amount of powerPerp to burn * @param _withdrawAmount amount of eth to withdraw * @return amount of wPowerPerp burned */ function burnPowerPerpAmount( uint256 _vaultId, uint256 _powerPerpAmount, uint256 _withdrawAmount ) external notPaused nonReentrant returns (uint256) { return _burnAndWithdraw(msg.sender, _vaultId, _powerPerpAmount, _withdrawAmount, false); } /** * @notice after the system is shutdown, insolvent vaults need to be have their uniswap v3 token assets withdrawn by force * @notice if a vault has a uniswap v3 position in it, anyone can call to withdraw uniswap v3 token assets, reducing debt and increasing collateral in the vault * @dev the caller won't get any bounty. this is expected to be used for insolvent vaults in shutdown * @param _vaultId vault containing uniswap v3 position to liquidate */ function reduceDebtShutdown(uint256 _vaultId) external isShutdown nonReentrant { VaultLib.Vault memory cachedVault = vaults[_vaultId]; _reduceDebt( cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, normalizationFactor, false ); _writeVault(_vaultId, cachedVault); } /** * @notice withdraw assets from uniswap v3 position, reducing debt and increasing collateral in the vault * @dev the caller won't get any bounty. this is expected to be used by vault owner * @param _vaultId target vault */ function reduceDebt(uint256 _vaultId) external notPaused nonReentrant { _checkCanModifyVault(_vaultId, msg.sender); uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; _reduceDebt(cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, cachedNormFactor, false); _writeVault(_vaultId, cachedVault); } /** * @notice if a vault is under the 150% collateral ratio, anyone can liquidate the vault by burning wPowerPerp * @dev liquidator can get back (wPowerPerp burned) * (index price) * (normalizationFactor) * 110% in collateral * @dev normally can only liquidate 50% of a vault's debt * @dev if a vault is under dust limit after a liquidation can fully liquidate * @dev will attempt to reduceDebt first, and can earn a bounty if sucessful * @param _vaultId vault to liquidate * @param _maxDebtAmount max amount of wPowerPerpetual to repay * @return amount of wPowerPerp repaid */ function liquidate(uint256 _vaultId, uint256 _maxDebtAmount) external notPaused nonReentrant returns (uint256) { _checkVaultId(_vaultId); uint256 cachedNormFactor = _applyFunding(); VaultLib.Vault memory cachedVault = vaults[_vaultId]; require(!_isVaultSafe(cachedVault, cachedNormFactor), "C12"); // try to save target vault before liquidation by reducing debt uint256 bounty = _reduceDebt( cachedVault, IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId), _vaultId, cachedNormFactor, true ); // if vault is safe after saving, pay bounty and return early if (_isVaultSafe(cachedVault, cachedNormFactor)) { _writeVault(_vaultId, cachedVault); payable(msg.sender).sendValue(bounty); return 0; } // add back the bounty amount, liquidators onlly get reward from liquidation cachedVault.addEthCollateral(bounty); // if the vault is still not safe after saving, liquidate it (uint256 debtAmount, uint256 collateralPaid) = _liquidate( cachedVault, _maxDebtAmount, cachedNormFactor, msg.sender ); emit Liquidate(msg.sender, _vaultId, debtAmount, collateralPaid); _writeVault(_vaultId, cachedVault); // pay the liquidator payable(msg.sender).sendValue(collateralPaid); return debtAmount; } /** * @notice authorize an address to modify the vault * @dev can be revoke by setting address to 0 * @param _vaultId id of the vault * @param _operator new operator address */ function updateOperator(uint256 _vaultId, address _operator) external { require(IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId) == msg.sender, "C25"); vaults[_vaultId].operator = _operator; emit UpdateOperator(msg.sender, _vaultId, _operator); } /** * @notice set the recipient who will receive the fee * @dev this should be a contract handling insurance * @param _newFeeRecipient new fee recipient */ function setFeeRecipient(address _newFeeRecipient) external onlyOwner { require(_newFeeRecipient != address(0), "C13"); emit FeeRecipientUpdated(feeRecipient, _newFeeRecipient); feeRecipient = _newFeeRecipient; } /** * @notice set the fee rate when user mints * @dev this function cannot be called if the feeRecipient is still un-set * @param _newFeeRate new fee rate in basis points. can't be higher than 1% */ function setFeeRate(uint256 _newFeeRate) external onlyOwner { require(feeRecipient != address(0), "C14"); require(_newFeeRate <= 100, "C15"); emit FeeRateUpdated(feeRate, _newFeeRate); feeRate = _newFeeRate; } /** * @notice pause (if not paused) and then immediately shutdown the system, can be called when paused already * @dev this bypasses the check on number of pauses or time based checks, but is irreversible and enables emergency settlement */ function shutDown() external onlyOwner notShutdown { isSystemPaused = true; isShutDown = true; indexForSettlement = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, TWAP_PERIOD, false ); } /** * @notice pause the system for up to 24 hours after which any one can unpause * @dev can only be called for 365 days since the contract was launched or 4 times */ function pause() external onlyOwner notShutdown notPaused { require(pausesLeft > 0, "C16"); uint256 timeSinceDeploy = block.timestamp.sub(deployTimestamp); require(timeSinceDeploy < PAUSE_TIME_LIMIT, "C17"); isSystemPaused = true; pausesLeft -= 1; lastPauseTime = block.timestamp; emit Paused(pausesLeft); } /** * @notice unpause the contract * @dev anyone can unpause the contract after 24 hours */ function unPauseAnyone() external isPaused notShutdown { require(block.timestamp > (lastPauseTime + 1 days), "C18"); isSystemPaused = false; emit UnPaused(msg.sender); } /** * @notice unpause the contract * @dev owner can unpause at any time */ function unPauseOwner() external onlyOwner isPaused notShutdown { isSystemPaused = false; emit UnPaused(msg.sender); } /** * @notice redeem wPowerPerp for (settlement index value) * normalizationFactor when the system is shutdown * @param _wPerpAmount amount of wPowerPerp to burn */ function redeemLong(uint256 _wPerpAmount) external isShutdown nonReentrant { IWPowerPerp(wPowerPerp).burn(msg.sender, _wPerpAmount); uint256 longValue = Power2Base._getLongSettlementValue(_wPerpAmount, indexForSettlement, normalizationFactor); payable(msg.sender).sendValue(longValue); emit RedeemLong(msg.sender, _wPerpAmount, longValue); } /** * @notice redeem short position when the system is shutdown * @dev short position is redeemed by valuing the debt at the (settlement index value) * normalizationFactor * @param _vaultId vault id */ function redeemShort(uint256 _vaultId) external isShutdown nonReentrant { _checkCanModifyVault(_vaultId, msg.sender); VaultLib.Vault memory cachedVault = vaults[_vaultId]; uint256 cachedNormFactor = normalizationFactor; _reduceDebt(cachedVault, msg.sender, _vaultId, cachedNormFactor, false); uint256 debt = Power2Base._getLongSettlementValue( cachedVault.shortAmount, indexForSettlement, cachedNormFactor ); // if the debt is more than collateral, this line will revert uint256 excess = uint256(cachedVault.collateralAmount).sub(debt); // reset the vault but don't burn the nft, just because people may want to keep it cachedVault.shortAmount = 0; cachedVault.collateralAmount = 0; _writeVault(_vaultId, cachedVault); payable(msg.sender).sendValue(excess); emit RedeemShort(msg.sender, _vaultId, excess); } /** * @notice update the normalization factor as a way to pay funding */ function applyFunding() external notPaused { _applyFunding(); } /** * @notice add eth into a contract. used in case contract has insufficient eth to pay for settlement transactions */ function donate() external payable isShutdown {} /** * @notice fallback function to accept eth */ receive() external payable { require(msg.sender == weth, "C19"); } /* * ====================== * | Internal Functions | * ====================== */ /** * @notice check if a vaultId is valid, reverts if it's not valid * @param _vaultId the id to check */ function _checkVaultId(uint256 _vaultId) internal view { require(_vaultId > 0 && _vaultId < IShortPowerPerp(shortPowerPerp).nextId(), "C20"); } /** * @notice check if an address can modify a vault * @param _vaultId the id of the vault to check if can be modified by _account * @param _account the address to check if can modify the vault */ function _checkCanModifyVault(uint256 _vaultId, address _account) internal view { require( IShortPowerPerp(shortPowerPerp).ownerOf(_vaultId) == _account || vaults[_vaultId].operator == _account, "C25" ); } /** * @notice wrapper function which open a vault, add collateral and mint wPowerPerp * @param _account account to receive wPowerPerp * @param _vaultId id of the vault * @param _mintAmount amount to mint * @param _depositAmount amount of eth as collateral * @param _uniTokenId id of uniswap v3 position token * @param _isWAmount if the input amount is wPowerPerp (as opposed to rebasing powerPerp) * @return vaultId * @return total minted wPowerPower amount */ function _openDepositMint( address _account, uint256 _vaultId, uint256 _mintAmount, uint256 _depositAmount, uint256 _uniTokenId, bool _isWAmount ) internal returns (uint256, uint256) { uint256 cachedNormFactor = _applyFunding(); uint256 depositAmountWithFee = _depositAmount; uint256 wPowerPerpAmount = _isWAmount ? _mintAmount : _mintAmount.mul(ONE).div(cachedNormFactor); uint256 feeAmount; VaultLib.Vault memory cachedVault; // load vault or create new a new one if (_vaultId == 0) { (_vaultId, cachedVault) = _openVault(_account); } else { // make sure we're not accessing an unexistent vault. _checkVaultId(_vaultId); cachedVault = vaults[_vaultId]; } if (wPowerPerpAmount > 0) { (feeAmount, depositAmountWithFee) = _getFee( cachedVault, wPowerPerpAmount, _depositAmount, cachedNormFactor ); _mintWPowerPerp(cachedVault, _account, _vaultId, wPowerPerpAmount); } if (_depositAmount > 0) _addEthCollateral(cachedVault, _vaultId, depositAmountWithFee); if (_uniTokenId != 0) _depositUniPositionToken(cachedVault, _account, _vaultId, _uniTokenId); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); // pay insurance fee if (feeAmount > 0) payable(feeRecipient).sendValue(feeAmount); return (_vaultId, wPowerPerpAmount); } /** * @notice wrapper function to burn wPowerPerp and redeem collateral * @param _account who should receive collateral * @param _vaultId id of the vault * @param _burnAmount amount of wPowerPerp to burn * @param _withdrawAmount amount of eth collateral to withdraw * @param _isWAmount true if the amount is wPowerPerp (as opposed to rebasing powerPerp) * @return total burned wPowerPower amount */ function _burnAndWithdraw( address _account, uint256 _vaultId, uint256 _burnAmount, uint256 _withdrawAmount, bool _isWAmount ) internal returns (uint256) { _checkVaultId(_vaultId); uint256 cachedNormFactor = _applyFunding(); uint256 wBurnAmount = _isWAmount ? _burnAmount : _burnAmount.mul(ONE).div(cachedNormFactor); VaultLib.Vault memory cachedVault = vaults[_vaultId]; if (wBurnAmount > 0) _burnWPowerPerp(cachedVault, _account, _vaultId, wBurnAmount); if (_withdrawAmount > 0) _withdrawCollateral(cachedVault, _account, _vaultId, _withdrawAmount); _checkVault(cachedVault, cachedNormFactor); _writeVault(_vaultId, cachedVault); if (_withdrawAmount > 0) payable(msg.sender).sendValue(_withdrawAmount); return wBurnAmount; } /** * @notice open a new vault * @dev create a new vault and bind it with a new short vault id * @param _recipient owner of new vault * @return id of the new vault * @return new in-memory vault */ function _openVault(address _recipient) internal returns (uint256, VaultLib.Vault memory) { uint256 vaultId = IShortPowerPerp(shortPowerPerp).mintNFT(_recipient); VaultLib.Vault memory vault = VaultLib.Vault({ NftCollateralId: 0, collateralAmount: 0, shortAmount: 0, operator: address(0) }); emit OpenVault(msg.sender, vaultId); return (vaultId, vault); } /** * @notice deposit uniswap v3 position token into a vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account account to transfer the uniswap v3 position from * @param _vaultId id of the vault * @param _uniTokenId uniswap position token id */ function _depositUniPositionToken( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _uniTokenId ) internal { //get tokens for uniswap NFT (, , address token0, address token1, , , , , , , , ) = INonfungiblePositionManager(uniswapPositionManager) .positions(_uniTokenId); // only check token0 and token1, ignore fee // if there are multiple wPowerPerp/weth pools with different fee rate, accept position tokens from any of them require((token0 == wPowerPerp && token1 == weth) || (token1 == wPowerPerp && token0 == weth), "C23"); _vault.addUniNftCollateral(_uniTokenId); INonfungiblePositionManager(uniswapPositionManager).transferFrom(_account, address(this), _uniTokenId); emit DepositUniPositionToken(msg.sender, _vaultId, _uniTokenId); } /** * @notice add eth collateral into a vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update. * @param _amount amount of eth adding to the vault */ function _addEthCollateral( VaultLib.Vault memory _vault, uint256 _vaultId, uint256 _amount ) internal { _vault.addEthCollateral(_amount); emit DepositCollateral(msg.sender, _vaultId, _amount); } /** * @notice remove uniswap v3 position token from the vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account where to send the uni position token to * @param _vaultId id of the vault */ function _withdrawUniPositionToken( VaultLib.Vault memory _vault, address _account, uint256 _vaultId ) internal { _checkCanModifyVault(_vaultId, _account); uint256 tokenId = _vault.NftCollateralId; _vault.removeUniNftCollateral(); INonfungiblePositionManager(uniswapPositionManager).transferFrom(address(this), _account, tokenId); emit WithdrawUniPositionToken(msg.sender, _vaultId, tokenId); } /** * @notice remove eth collateral from the vault * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account where to send collateral to * @param _vaultId id of the vault * @param _amount amount of eth to withdraw */ function _withdrawCollateral( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _amount ) internal { _checkCanModifyVault(_vaultId, _account); _vault.removeEthCollateral(_amount); emit WithdrawCollateral(msg.sender, _vaultId, _amount); } /** * @notice mint wPowerPerp (ERC20) to an account * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account account to receive wPowerPerp * @param _vaultId id of the vault * @param _wPowerPerpAmount wPowerPerp amount to mint */ function _mintWPowerPerp( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _wPowerPerpAmount ) internal { _checkCanModifyVault(_vaultId, _account); _vault.addShort(_wPowerPerpAmount); IWPowerPerp(wPowerPerp).mint(_account, _wPowerPerpAmount); emit MintShort(msg.sender, _wPowerPerpAmount, _vaultId); } /** * @notice burn wPowerPerp (ERC20) from an account * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _account account burning the wPowerPerp * @param _vaultId id of the vault * @param _wPowerPerpAmount wPowerPerp amount to burn */ function _burnWPowerPerp( VaultLib.Vault memory _vault, address _account, uint256 _vaultId, uint256 _wPowerPerpAmount ) internal { _vault.removeShort(_wPowerPerpAmount); IWPowerPerp(wPowerPerp).burn(_account, _wPowerPerpAmount); emit BurnShort(msg.sender, _wPowerPerpAmount, _vaultId); } /** * @notice liquidate a vault, pay the liquidator * @dev liquidator can only liquidate at most 1/2 of the vault in 1 transaction * @dev this function will update the vault memory in-place * @param _vault the Vault memory to update * @param _maxWPowerPerpAmount maximum debt amount liquidator is willing to repay * @param _normalizationFactor current normalization factor * @param _liquidator liquidator address to receive eth * @return debtAmount amount of wPowerPerp repaid (burn from the vault) * @return collateralToPay amount of collateral paid to liquidator */ function _liquidate( VaultLib.Vault memory _vault, uint256 _maxWPowerPerpAmount, uint256 _normalizationFactor, address _liquidator ) internal returns (uint256, uint256) { (uint256 liquidateAmount, uint256 collateralToPay) = _getLiquidationResult( _maxWPowerPerpAmount, uint256(_vault.shortAmount), uint256(_vault.collateralAmount), _normalizationFactor ); // if the liquidator didn't specify enough wPowerPerp to burn, revert. require(_maxWPowerPerpAmount >= liquidateAmount, "C21"); IWPowerPerp(wPowerPerp).burn(_liquidator, liquidateAmount); _vault.removeShort(liquidateAmount); _vault.removeEthCollateral(collateralToPay); (, bool isDust) = _getVaultStatus(_vault, _normalizationFactor); require(!isDust, "C22"); return (liquidateAmount, collateralToPay); } /** * @notice redeem uniswap v3 position in a vault for its constituent eth and wSqueeth * @notice this will increase vault collateral by the amount of eth, and decrease debt by the amount of wSqueeth * @dev will be executed before liquidation if there's an NFT in the vault * @dev pays a 2% bounty to the liquidator if called by liquidate() * @dev will update the vault memory in-place * @param _vault the Vault memory to update * @param _owner account to send any excess * @param _payBounty true if paying caller 2% bounty * @return bounty amount of bounty paid for liquidator */ function _reduceDebt( VaultLib.Vault memory _vault, address _owner, uint256 _vaultId, uint256 _normalizationFactor, bool _payBounty ) internal returns (uint256) { uint256 nftId = _vault.NftCollateralId; if (nftId == 0) return 0; (uint256 withdrawnEthAmount, uint256 withdrawnWPowerPerpAmount) = _redeemUniToken(nftId); // change weth back to eth if (withdrawnEthAmount > 0) IWETH9(weth).withdraw(withdrawnEthAmount); (uint256 burnAmount, uint256 excess, uint256 bounty) = _getReduceDebtResultInVault( _vault, withdrawnEthAmount, withdrawnWPowerPerpAmount, _normalizationFactor, _payBounty ); if (excess > 0) IWPowerPerp(wPowerPerp).transfer(_owner, excess); if (burnAmount > 0) IWPowerPerp(wPowerPerp).burn(address(this), burnAmount); emit ReduceDebt( msg.sender, _vaultId, withdrawnEthAmount, withdrawnWPowerPerpAmount, burnAmount, excess, bounty ); return bounty; } /** * @notice pay fee recipient * @dev pay in eth from either the vault or the deposit amount * @param _vault the Vault memory to update * @param _wSqueethAmount the amount of wSqueeth minting * @param _depositAmount the amount of eth depositing or withdrawing * @param _normalizationFactor current normalization factor * @return the amount of actual deposited eth into the vault, this is less than the original amount if a fee was taken */ function _getFee( VaultLib.Vault memory _vault, uint256 _wSqueethAmount, uint256 _depositAmount, uint256 _normalizationFactor ) internal view returns (uint256, uint256) { uint256 cachedFeeRate = feeRate; if (cachedFeeRate == 0) return (uint256(0), _depositAmount); uint256 depositAmountAfterFee; uint256 ethEquivalentMinted = Power2Base._getDebtValueInEth( _wSqueethAmount, oracle, ethQuoteCurrencyPool, weth, quoteCurrency, _normalizationFactor ); uint256 feeAmount = ethEquivalentMinted.mul(cachedFeeRate).div(10000); // if fee can be paid from deposited collateral, pay from _depositAmount if (_depositAmount > feeAmount) { depositAmountAfterFee = _depositAmount.sub(feeAmount); // if not, adjust the vault to pay from the vault collateral } else { _vault.removeEthCollateral(feeAmount); depositAmountAfterFee = _depositAmount; } //return the fee and deposit amount, which has only been reduced by a fee if it is paid out of the deposit amount return (feeAmount, depositAmountAfterFee); } /** * @notice write vault to storage * @dev writes to vaults mapping */ function _writeVault(uint256 _vaultId, VaultLib.Vault memory _vault) private { vaults[_vaultId] = _vault; } /** * @dev redeem a uni position token and get back wPowerPerp and eth * @param _uniTokenId uniswap v3 position token id * @return wethAmount amount of weth withdrawn from uniswap * @return wPowerPerpAmount amount of wPowerPerp withdrawn from uniswap */ function _redeemUniToken(uint256 _uniTokenId) internal returns (uint256, uint256) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(uniswapPositionManager); (, , uint128 liquidity, , ) = VaultLib._getUniswapPositionInfo(uniswapPositionManager, _uniTokenId); // prepare parameters to withdraw liquidity from uniswap v3 position manager INonfungiblePositionManager.DecreaseLiquidityParams memory decreaseParams = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: _uniTokenId, liquidity: liquidity, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); positionManager.decreaseLiquidity(decreaseParams); // withdraw max amount of weth and wPowerPerp from uniswap INonfungiblePositionManager.CollectParams memory collectParams = INonfungiblePositionManager.CollectParams({ tokenId: _uniTokenId, recipient: address(this), amount0Max: uint128(-1), amount1Max: uint128(-1) }); (uint256 collectedToken0, uint256 collectedToken1) = positionManager.collect(collectParams); return isWethToken0 ? (collectedToken0, collectedToken1) : (collectedToken1, collectedToken0); } /** * @notice update the normalization factor as a way to pay in-kind funding * @dev the normalization factor scales amount of debt that must be repaid, effecting an interest rate paid between long and short positions * @return new normalization factor **/ function _applyFunding() internal returns (uint256) { // only update the norm factor once per block if (lastFundingUpdateTimestamp == block.timestamp) return normalizationFactor; uint256 newNormalizationFactor = _getNewNormalizationFactor(); emit NormalizationFactorUpdated( normalizationFactor, newNormalizationFactor, lastFundingUpdateTimestamp, block.timestamp ); // the following will be batch into 1 SSTORE because of type uint128 normalizationFactor = newNormalizationFactor.toUint128(); lastFundingUpdateTimestamp = block.timestamp.toUint128(); return newNormalizationFactor; } /** * @dev calculate new normalization factor base on the current timestamp * @return new normalization factor if funding happens in the current block */ function _getNewNormalizationFactor() internal view returns (uint256) { uint32 period = block.timestamp.sub(lastFundingUpdateTimestamp).toUint32(); if (period == 0) { return normalizationFactor; } // make sure we use the same period for mark and index uint32 periodForOracle = _getConsistentPeriodForOracle(period); // avoid reading normalizationFactor from storage multiple times uint256 cacheNormFactor = normalizationFactor; uint256 mark = Power2Base._getDenormalizedMark( periodForOracle, oracle, wPowerPerpPool, ethQuoteCurrencyPool, weth, quoteCurrency, wPowerPerp, cacheNormFactor ); uint256 index = Power2Base._getIndex(periodForOracle, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); uint256 rFunding = (ONE.mul(uint256(period))).div(FUNDING_PERIOD); // floor mark to be at least LOWER_MARK_RATIO of index uint256 lowerBound = index.mul(LOWER_MARK_RATIO).div(ONE); if (mark < lowerBound) { mark = lowerBound; } else { // cap mark to be at most UPPER_MARK_RATIO of index uint256 upperBound = index.mul(UPPER_MARK_RATIO).div(ONE); if (mark > upperBound) mark = upperBound; } // newNormFactor = (mark / ( (1+rFunding) * mark - index * rFunding )) * oldNormaFactor uint256 multiplier = mark.mul(ONE_ONE).div((ONE.add(rFunding)).mul(mark).sub(index.mul(rFunding))); // multiply by 1e36 to keep multiplier in 18 decimals return cacheNormFactor.mul(multiplier).div(ONE); } /** * @notice check if vault has enough collateral and is not a dust vault * @dev revert if vault has insufficient collateral or is a dust vault * @param _vault the Vault memory to update * @param _normalizationFactor normalization factor */ function _checkVault(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view { (bool isSafe, bool isDust) = _getVaultStatus(_vault, _normalizationFactor); require(isSafe, "C24"); require(!isDust, "C22"); } /** * @notice check that the vault has enough collateral * @param _vault in-memory vault * @param _normalizationFactor normalization factor * @return true if the vault is properly collateralized */ function _isVaultSafe(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view returns (bool) { (bool isSafe, ) = _getVaultStatus(_vault, _normalizationFactor); return isSafe; } /** * @notice return if the vault is properly collateralized and if it is a dust vault * @param _vault the Vault memory to update * @param _normalizationFactor normalization factor * @return true if the vault is safe * @return true if the vault is a dust vault */ function _getVaultStatus(VaultLib.Vault memory _vault, uint256 _normalizationFactor) internal view returns (bool, bool) { uint256 scaledEthPrice = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, TWAP_PERIOD, true // do not call more than maximum period so it does not revert ); return VaultLib.getVaultStatus( _vault, uniswapPositionManager, _normalizationFactor, scaledEthPrice, MIN_COLLATERAL, IOracle(oracle).getTimeWeightedAverageTickSafe(wPowerPerpPool, TWAP_PERIOD), isWethToken0 ); } /** * @notice get the expected excess, burnAmount and bounty if Uniswap position token got burned * @dev this function will update the vault memory in-place * @return burnAmount amount of wSqueeth that should be burned * @return wPowerPerpExcess amount of wSqueeth that should be send to the vault owner * @return bounty amount of bounty should be paid out to caller */ function _getReduceDebtResultInVault( VaultLib.Vault memory _vault, uint256 nftEthAmount, uint256 nftWPowerperpAmount, uint256 _normalizationFactor, bool _payBounty ) internal view returns ( uint256, uint256, uint256 ) { uint256 bounty; if (_payBounty) bounty = _getReduceDebtBounty(nftEthAmount, nftWPowerperpAmount, _normalizationFactor); uint256 burnAmount = nftWPowerperpAmount; uint256 wPowerPerpExcess; if (nftWPowerperpAmount > _vault.shortAmount) { wPowerPerpExcess = nftWPowerperpAmount.sub(_vault.shortAmount); burnAmount = _vault.shortAmount; } _vault.removeShort(burnAmount); _vault.removeUniNftCollateral(); _vault.addEthCollateral(nftEthAmount); _vault.removeEthCollateral(bounty); return (burnAmount, wPowerPerpExcess, bounty); } /** * @notice get how much bounty you can get by helping a vault reducing the debt. * @dev bounty is 2% of the total value of the position token * @param _ethWithdrawn amount of eth withdrawn from uniswap by redeeming the position token * @param _wPowerPerpReduced amount of wPowerPerp withdrawn from uniswap by redeeming the position token * @param _normalizationFactor normalization factor */ function _getReduceDebtBounty( uint256 _ethWithdrawn, uint256 _wPowerPerpReduced, uint256 _normalizationFactor ) internal view returns (uint256) { return Power2Base ._getDebtValueInEth( _wPowerPerpReduced, oracle, ethQuoteCurrencyPool, weth, quoteCurrency, _normalizationFactor ) .add(_ethWithdrawn) .mul(REDUCE_DEBT_BOUNTY) .div(ONE); } /** * @notice get the expected wPowerPerp needed to liquidate a vault. * @dev a liquidator cannot liquidate more than half of a vault, unless only liquidating half of the debt will make the vault a "dust vault" * @dev a liquidator cannot take out more collateral than the vault holds * @param _maxWPowerPerpAmount the max amount of wPowerPerp willing to pay * @param _vaultShortAmount the amount of short in the vault * @param _maxWPowerPerpAmount the amount of collateral in the vault * @param _normalizationFactor normalization factor * @return finalLiquidateAmount the amount that should be liquidated. This amount can be higher than _maxWPowerPerpAmount, which should be checked * @return collateralToPay final amount of collateral paying out to the liquidator */ function _getLiquidationResult( uint256 _maxWPowerPerpAmount, uint256 _vaultShortAmount, uint256 _vaultCollateralAmount, uint256 _normalizationFactor ) internal view returns (uint256, uint256) { // try limiting liquidation amount to half of the vault debt (uint256 finalLiquidateAmount, uint256 collateralToPay) = _getSingleLiquidationAmount( _maxWPowerPerpAmount, _vaultShortAmount.div(2), _normalizationFactor ); if (_vaultCollateralAmount > collateralToPay) { if (_vaultCollateralAmount.sub(collateralToPay) < MIN_COLLATERAL) { // the vault is left with dust after liquidation, allow liquidating full vault // calculate the new liquidation amount and collateral again based on the new limit (finalLiquidateAmount, collateralToPay) = _getSingleLiquidationAmount( _maxWPowerPerpAmount, _vaultShortAmount, _normalizationFactor ); } } // check if final collateral to pay is greater than vault amount. // if so the system only pays out the amount the vault has, which may not be profitable if (collateralToPay > _vaultCollateralAmount) { // force liquidator to pay full debt amount finalLiquidateAmount = _vaultShortAmount; collateralToPay = _vaultCollateralAmount; } return (finalLiquidateAmount, collateralToPay); } /** * @notice determine how much wPowerPerp to liquidate, and how much collateral to return * @param _maxInputWAmount maximum wPowerPerp amount liquidator is willing to repay * @param _maxLiquidatableWAmount maximum wPowerPerp amount a liquidator is allowed to repay * @param _normalizationFactor normalization factor * @return finalWAmountToLiquidate amount of wPowerPerp the liquidator will burn * @return collateralToPay total collateral the liquidator will get */ function _getSingleLiquidationAmount( uint256 _maxInputWAmount, uint256 _maxLiquidatableWAmount, uint256 _normalizationFactor ) internal view returns (uint256, uint256) { uint256 finalWAmountToLiquidate = _maxInputWAmount > _maxLiquidatableWAmount ? _maxLiquidatableWAmount : _maxInputWAmount; uint256 collateralToPay = Power2Base._getDebtValueInEth( finalWAmountToLiquidate, oracle, ethQuoteCurrencyPool, weth, quoteCurrency, _normalizationFactor ); // add 10% bonus for liquidators collateralToPay = collateralToPay.add(collateralToPay.mul(LIQUIDATION_BOUNTY).div(ONE)); return (finalWAmountToLiquidate, collateralToPay); } /** * @notice get a period can be used to request a twap for 2 uniswap v3 pools * @dev if the period is greater than min(max_pool_1, max_pool_2), return min(max_pool_1, max_pool_2) * @param _period max period that we intend to use * @return fair period not greator than _period to be used for both pools. */ function _getConsistentPeriodForOracle(uint32 _period) internal view returns (uint32) { uint32 maxPeriodPool1 = IOracle(oracle).getMaxPeriod(ethQuoteCurrencyPool); uint32 maxPeriodPool2 = IOracle(oracle).getMaxPeriod(wPowerPerpPool); uint32 maxSafePeriod = maxPeriodPool1 > maxPeriodPool2 ? maxPeriodPool2 : maxPeriodPool1; return _period > maxSafePeriod ? maxSafePeriod : _period; } }
* @notice pause (if not paused) and then immediately shutdown the system, can be called when paused already @dev this bypasses the check on number of pauses or time based checks, but is irreversible and enables emergency settlement/
function shutDown() external onlyOwner notShutdown { isSystemPaused = true; isShutDown = true; indexForSettlement = Power2Base._getScaledTwap( oracle, ethQuoteCurrencyPool, weth, quoteCurrency, TWAP_PERIOD, false ); }
13,123,570
[ 1, 19476, 261, 430, 486, 17781, 13, 471, 1508, 7636, 5731, 326, 2619, 16, 848, 506, 2566, 1347, 17781, 1818, 225, 333, 17587, 281, 326, 866, 603, 1300, 434, 6790, 6117, 578, 813, 2511, 4271, 16, 1496, 353, 9482, 266, 2496, 1523, 471, 19808, 801, 24530, 26319, 806, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 9171, 4164, 1435, 3903, 1338, 5541, 486, 10961, 288, 203, 3639, 353, 3163, 28590, 273, 638, 31, 203, 3639, 353, 1555, 322, 4164, 273, 638, 31, 203, 3639, 770, 1290, 694, 88, 806, 273, 23783, 22, 2171, 6315, 588, 55, 12825, 23539, 438, 12, 203, 5411, 20865, 16, 203, 5411, 13750, 10257, 7623, 2864, 16, 203, 5411, 341, 546, 16, 203, 5411, 3862, 7623, 16, 203, 5411, 24722, 2203, 67, 28437, 16, 203, 5411, 629, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; /******************************************/ /* Owned starts here */ /******************************************/ 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, "Sender not authorized."); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "0x00 address not allowed."); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner, "Sender not authorized."); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************/ /* TokenERC20 starts here */ /******************************************/ contract TokenERC20 { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); constructor() public { decimals = 18; // decimals totalSupply = 0; // initialSupply name = "LOOiX"; // Set the name for display purposes symbol = "LOOIX"; // Set the symbol for display purposes } /** * @dev Transfer token for a specified addresses * @param _from The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _transfer(address _from, address _to, uint256 _value) internal { require(_value > 0, "Transferred value has to be grater than 0."); require(_to != address(0), "0x00 address not allowed."); // Prevent transfer to 0x0 address. require(balanceOf[_from] >= _value, "Not enough funds on sender address."); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to], "Overflow protection."); // Check for overflows balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * @dev Transfer tokens * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns(bool success) { _transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from other address * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { require(_value <= allowance[_from][msg.sender], "Funds not approved."); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * @dev Set allowance for other address * @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) { require(_value == 0 || allowance[msg.sender][_spender] == 0, "Approved funds or value are not 0."); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } /******************************************/ /* TokenStaking starts here */ /******************************************/ contract TokenStaking { uint256 internal stakeID; uint256 internal threeMonthTime; uint256 internal threeMonthPercentage; uint256 internal sixMonthTime; uint256 internal sixMonthPercentage; uint256 internal twelveMonthTime; uint256 internal twelveMonthPercentage; struct stakeInfo // Struct for user vestings { uint256 endDate; uint256 amount; address initiator; address receiver; } mapping(address => uint256) public stakedBalanceOf; mapping(uint256 => stakeInfo) internal vestings; mapping(address => uint256[]) internal userVestingIDs; enum StakeOption {three, six, twelve} constructor() TokenStaking() public { stakeID = 0; threeMonthTime = 91 days; threeMonthPercentage = 1005012520859401063; // e**(0.02*0.25) sixMonthTime = 182 days; sixMonthPercentage = 1020201340026755810; // e**(0.04*0.5) twelveMonthTime = 365 days; twelveMonthPercentage = 1061836546545359622; // e**(0.06*1.0) } /** * @dev Function to get the stake info from a corresponding ID. * @param _id uint256 The ID from which the stake info should be read. * @return endDate uint256 specifying the seconds since the UNIX Epoch. amount uint256 specifying the amount that was staked plus the stake bonus. */ function getStakeInfo(uint256 _id) external view returns(uint256 endDate, uint256 amount, address receiver, address initiator) { return (vestings[_id].endDate, vestings[_id].amount, vestings[_id].receiver, vestings[_id].initiator); } /** * @dev Function to get the stake IDs from a given address. * @param _address address The address which staked tokens. * @return Ids uint256[] An array of stake IDs from the given address. */ function getStakeIDs(address _address) external view returns(uint256[] memory Ids) { return userVestingIDs[_address]; } /** * @dev Stake an amount of tokens with one of three options. * @param _amount uint256 The amount of tokens which will be staked. * @param _option StakeOption An enum which decides how long a stake will be frozen (only 0, 1 and 2 are valid values). * @return totalSupplyIncreaseds uint256 The total increase in supply from the staked tokens. */ function _stake(uint256 _amount, StakeOption _option, address _receiver) internal returns(uint256 totalSupplyIncrease) { require(_option >= StakeOption.three && _option <= StakeOption.twelve); stakeInfo memory stakeStruct; stakeStruct.endDate = 0; stakeStruct.amount = 0; stakeStruct.initiator = msg.sender; stakeStruct.receiver = address(0); uint256 tempIncrease; if (_option == StakeOption.three) { stakeStruct.endDate = now + threeMonthTime; stakeStruct.amount = _amount * threeMonthPercentage / (10**18); stakeStruct.initiator = msg.sender; stakeStruct.receiver = _receiver; tempIncrease = (_amount * (threeMonthPercentage - (10**18)) / (10**18)); } else if (_option == StakeOption.six) { stakeStruct.endDate = now + sixMonthTime; stakeStruct.amount = _amount * sixMonthPercentage / (10**18); stakeStruct.initiator = msg.sender; stakeStruct.receiver = _receiver; tempIncrease = (_amount * (sixMonthPercentage - (10**18)) / (10**18)); } else if (_option == StakeOption.twelve) { stakeStruct.endDate = now + twelveMonthTime; stakeStruct.amount = _amount * twelveMonthPercentage / (10**18); stakeStruct.initiator = msg.sender; stakeStruct.receiver = _receiver; tempIncrease = (_amount * (twelveMonthPercentage - (10**18)) / (10**18)); } stakeID = stakeID + 1; vestings[stakeID] = stakeStruct; _setVestingID(stakeID, stakeStruct.receiver); stakedBalanceOf[msg.sender] += stakeStruct.amount; return tempIncrease; } /** * @dev Function to set a new vesting ID on the userVestingIDs mapping. Free ID slots in the array will be overwritten. * @param _id uint256 The new ID that has to be written in the corresponding mapping. */ function _setVestingID(uint256 _id, address _receiver) internal { bool tempEntryWritten = false; uint256 arrayLength = userVestingIDs[_receiver].length; if(arrayLength != 0) { for (uint256 i = 0; i < arrayLength; i++) { if (userVestingIDs[_receiver][i] == 0) { userVestingIDs[_receiver][i] = _id; tempEntryWritten = true; break; } } if(!tempEntryWritten) { userVestingIDs[_receiver].push(_id); } } else { userVestingIDs[_receiver].push(_id); } } /** * @dev Redeem the staked tokens. * @return amount uint256 The amount that has been redeemed. */ function _redeem() internal returns(uint256 amount) { uint256[] memory IdArray = userVestingIDs[msg.sender]; uint256 tempAmount = 0; uint256 finalAmount = 0; address tempInitiator = address(0); for(uint256 i = 0; i < IdArray.length; i++) { if(IdArray[i] != 0 && vestings[IdArray[i]].endDate <= now) { tempInitiator = vestings[IdArray[i]].initiator; tempAmount = vestings[IdArray[i]].amount; stakedBalanceOf[tempInitiator] -= tempAmount; finalAmount += tempAmount; // delete the vesting history delete userVestingIDs[msg.sender][i]; delete vestings[IdArray[i]]; } } require(finalAmount > 0, "No funds to redeem."); return finalAmount; } } /******************************************/ /* LOOiXToken starts here */ /******************************************/ contract LOOiXToken is owned, TokenERC20, TokenStaking { bool public mintingActive; address public mintDelegate; uint256 public unlockAt; uint256 public ICO_totalSupply; uint256 internal constant MAX_UINT = 2**256 - 1; mapping(address => uint256) public allocations; event Stake(address indexed _target, uint256 _amount); event Redeem(address indexed _target, uint256 _amount); constructor() TokenERC20() public { mintingActive = true; mintDelegate = address(0); unlockAt; } /** * @dev Modifier defines addresses allowed to mint. */ modifier mintingAllowed { require(msg.sender == owner || msg.sender == mintDelegate, "Sender not authorized."); _; } /** * @dev Internal ERC20 transfer. */ function _transfer(address _from, address _to, uint256 _value) internal { require(_value > 0, "Transferred value has to be grater than 0."); // value has to be greater than 0 require(_to != address(0), "0x00 address not allowed."); // Prevent transfer to 0x0 address require(balanceOf[_from] >= _value, "Not enough funds on sender address."); // Check if the sender has enough require(balanceOf[_to] + _value >= balanceOf[_to], "Overflow protection."); // Check for overflows balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * @dev ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. * @param _from Address to transfer from. * @param _to Address to transfer to. * @param _value Amount to transfer. * @return Success of transfer. */ function transferFrom(address _from, address _to, uint _value) public returns (bool success) { uint256 allowanceTemp = allowance[_from][msg.sender]; require(allowanceTemp >= _value, "Funds not approved."); require(balanceOf[_from] >= _value, "Not enough funds on sender address."); require(balanceOf[_to] + _value >= balanceOf[_to], "Overflow protection."); balanceOf[_to] += _value; balanceOf[_from] -= _value; if (allowanceTemp < MAX_UINT) { allowance[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } /** * @dev Set new mintDelegate address * @param _newDelegate The address authorized to mint */ function setMintDelegate(address _newDelegate) external onlyOwner { require(_newDelegate != address(0), "0x00 address not allowed."); mintDelegate = _newDelegate; } /** * @dev Set unlimited allowance for other address * @param _controllerAddress The address authorized to spend */ function giveAccess(address _controllerAddress) external { require(msg.sender != owner, "Owner of contract can not use this function."); require(_controllerAddress != address(0), "0x00 address not allowed."); allowance[msg.sender][_controllerAddress] = MAX_UINT; emit Approval(msg.sender, _controllerAddress, MAX_UINT); } /** * @dev Set allowance for other address to 0 * @param _controllerAddress The address authorized to spend */ function revokeAccess(address _controllerAddress) external { require(_controllerAddress != address(0), "0x00 address not allowed."); allowance[msg.sender][_controllerAddress] = 0; } /** * @dev Withdraw all LOOiX on the contract. */ function withdrawLOOiX() external onlyOwner { require(balanceOf[address(this)] > 0, "No funds available."); _transfer(address(this), owner, balanceOf[address(this)]); } /** * @dev Bulk mint function for airdrops. * @param _address Address array to mint to. * @param _mintAmount Amount array to mint. */ function mintTokenBulk(address[] _address, uint256[] _mintAmount) external mintingAllowed { require(mintingActive, "The mint functions are not available anymore."); uint256 tempAmount = 0; for (uint256 i = 0; i < _address.length; i++) { if(balanceOf[_address[i]] + _mintAmount[i] >= balanceOf[_address[i]]) { balanceOf[_address[i]] += _mintAmount[i] * (10**18); tempAmount += _mintAmount[i] * (10**18); emit Transfer(address(0), _address[i], _mintAmount[i] * (10**18)); } } totalSupply += tempAmount; } /** * @dev Mint function for creating new tokens. * @param _target Address to mint to. * @param _mintAmount Amount to mint. */ function mintToken(address _target, uint256 _mintAmount) public mintingAllowed { require(mintingActive, "The mint functions are not available anymore."); require(_target != address(0), "0x00 address not allowed."); balanceOf[_target] += _mintAmount * (10**18); totalSupply += _mintAmount * (10**18); emit Transfer(address(0), _target, _mintAmount * (10**18)); } /** * @dev Stops the minting of the token. After this function is called, no new tokens can be minted using the mintToken or mintTokenBulk functions. Irreversible. */ function terminateMinting() external onlyOwner { require(mintingActive, "The mint functions are not available anymore."); uint256 tempTotalSupply = totalSupply; tempTotalSupply = tempTotalSupply + (tempTotalSupply * 666666666666666666 / 10**18); totalSupply = tempTotalSupply; ICO_totalSupply = tempTotalSupply; mintingActive = false; unlockAt = now + 365 days; // 40% of the total token supply allocations[0xefbDBA37BD0e825d43bac88Ce570dcEFf50373C2] = tempTotalSupply * 9500 / 100000; // 9.5% - Founders Pot. allocations[0x75dE233590c8Dd593CE1bB89d68e9f18Ecdf34C8] = tempTotalSupply * 9500 / 100000; // 9.5% - Development and Management. allocations[0x357C2e4253389CE79440e867E9De14E17Bb97D2E] = tempTotalSupply * 3120 / 100000; // 3.12% - Bonuspool. allocations[0xf35FF681cbb69b47488269CE2BA5CaA34133813A] = tempTotalSupply * 14250 / 100000; // 14.25% - Marketing. balanceOf[0x2A809456adf8bd5A79D598e880f7Bd78e11B4A1c] += tempTotalSupply * 242 / 100000; balanceOf[0x36c321017a8d8655ec7a2b862328678932E53b87] += tempTotalSupply * 242 / 100000; balanceOf[0xc9ebc197Ee00C1E231817b4eb38322C364cFCFCD] += tempTotalSupply * 242 / 100000; balanceOf[0x2BE34a67491c6b1f8e0cA3BAA1249c90686CF6FB] += tempTotalSupply * 726 / 100000; balanceOf[0x1cF6725538AAcC9574108845D58cF2e89f62bbE9] += tempTotalSupply * 4 / 100000; balanceOf[0xc6a3B6ED936bD18FD72e0ae2D50A10B82EF79851] += tempTotalSupply * 130 / 100000; balanceOf[0x204Fb77569ca24C09e1425f979141536B89449E3] += tempTotalSupply * 130 / 100000; balanceOf[0xbE3Ece67B61Ef6D3Fd0F8b159d16A80BB04C0F7B] += tempTotalSupply * 164 / 100000; // Bonuspool. balanceOf[0x731953d4c9A01c676fb6b013688AA8D512F5Ec03] += tempTotalSupply * 500 / 100000; // Development and Management. balanceOf[0x84A81f3B42BD99Fd435B1498316F8705f84192bC] += tempTotalSupply * 500 / 100000; // Founders Pot. balanceOf[0xEAeC9b7382e5abEBe76Fc7BDd2Dc22BA1a338918] += tempTotalSupply * 750 / 100000; // Marketing. } /** * @dev Public unlock allocated Tokens. */ function unlock() public { require(!mintingActive, "Function not available as long as minting is possible."); require(now > unlockAt, "Unlock date not reached."); require(allocations[msg.sender] > 0, "No tokens to unlock."); uint256 tempAmount; tempAmount = allocations[msg.sender]; allocations[msg.sender] = 0; balanceOf[msg.sender] += tempAmount; } /** * @dev Public stake function to stake a given amount of tokens for one of the three options. * @param _amount Amount to stake. * @param _option StakeOption enum with values from 0 to 2. * @return Success of stake. */ function stake(uint256 _amount, StakeOption _option, address _receiver) external returns(bool success) { require(!mintingActive, "Function not available as long as minting is possible."); require(balanceOf[msg.sender] >= _amount, "Not enough funds on sender address."); require(_amount >= 100*(10**18), "Amount is less than 100 token."); require(_receiver != address(0), "0x00 address not allowed."); uint256 supplyIncrease; uint256 finalBalance; supplyIncrease = _stake(_amount, _option, _receiver); totalSupply += supplyIncrease; balanceOf[msg.sender] -= _amount; finalBalance = _amount + supplyIncrease; emit Stake(_receiver, _amount); emit Transfer(msg.sender, _receiver, finalBalance); return true; } /** * @dev Public redeem function to redeem all redeemable tokens. */ function redeem() public { require(userVestingIDs[msg.sender].length > 0, "No funds to redeem."); uint256 amount; amount = _redeem(); balanceOf[msg.sender] += amount; emit Redeem(msg.sender, amount); } }
Set the symbol for display purposes
symbol = "LOOIX";
13,026,124
[ 1, 694, 326, 3273, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 1502, 51, 12507, 14432, 5397, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../vendors/interfaces/IUniswapOracle.sol"; import "../vendors/libraries/UniswapV2Library.sol"; import "../vendors/libraries/FixedPoint.sol"; import "../vendors/libraries/SafeMath.sol"; import "../vendors/libraries/UniswapV2OracleLibrary.sol"; // sliding window oracle that uses observations collected over a window to provide moving price averages in the past // `windowSize` with a precision of `windowSize / granularity` // note this is a singleton oracle and only needs to be deployed once per desired parameters, which // differs from the simple oracle which must be deployed once per pair. contract UniswapOracle is IUniswapOracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } address public immutable factory; address public immutable tokenA; // USDT or BUSD address public immutable tokenB; // WETH // address public immutable factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // address public immutable tokenA = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // DAI // address public immutable tokenB = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; // WETH // the desired amount of time over which the moving average should be computed, e.g. 24 hours uint public immutable windowSize; // the number of observations stored for each pair, i.e. how many price observations are stored for the window. // as granularity increases from 1, more frequent updates are needed, but moving averages become more precise. // averages are computed over intervals with sizes in the range: // [windowSize - (windowSize / granularity) * 2, windowSize] // e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for // the period: // [now - [22 hours, 24 hours], now] uint8 public immutable granularity; // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public immutable periodSize; // mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; uint256 tmp; constructor(uint windowSize_, uint8 granularity_ ,address _factory, address _tokenA, address _tokenB) public { require(granularity_ > 1, 'SlidingWindowOracle: GRANULARITY'); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, 'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE' ); windowSize = windowSize_; granularity = granularity_; factory = _factory; tokenA = _tokenA; tokenB = _tokenB; } // returns the index of the observation corresponding to the given timestamp function observationIndexOf(uint timestamp) public view returns (uint8 index) { uint epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); } // returns the observation from the oldest epoch (at the beginning of the window) relative to the current time function getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); // no overflow issue. if observationIndex + 1 overflows, result is still zero. uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } function getFirstObservationInWindow2(address pair) external view returns (Observation memory firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); // no overflow issue. if observationIndex + 1 overflows, result is still zero. uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } // update the cumulative price for the observation at the current timestamp. each observation is updated at most // once per epoch period. function update() external override { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); // populate the array with empty observations (first call only) for (uint i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } // get the observation for the current period uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // we only want to commit updates once per period (i.e. windowSize / granularity) uint timeElapsed = block.timestamp - observation.timestamp; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; } } function getPair() external view override returns (address) { return UniswapV2Library.pairFor(factory, tokenA, tokenB); } function getPrice() external view returns (uint,uint) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); return (price0Cumulative,price1Cumulative); } // given the cumulative prices of the start and end of a period, and the length of the period, compute the average // price in terms of how much amount out is received for the amount in function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } // returns the amount out corresponding to the amount in for a given token using the moving average over the time // range [now - [windowSize, windowSize - periodSize * 2], now] // update must have been called for the bucket corresponding to timestamp `now - windowSize` function consult(address tokenIn, uint amountIn, address tokenOut) internal view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = getFirstObservationInWindow(pair); uint timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION'); // should never happen. require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED'); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function consultAB(uint amountIn) external view override returns (uint amountOut){ return consult(tokenA, amountIn, tokenB); } function consultBA(uint amountIn) external view override returns (uint amountOut){ return consult(tokenB, amountIn, tokenA); } function getTimeElapsed(address tokenIn, address tokenOut) external view override returns (uint) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = getFirstObservationInWindow(pair); uint timeElapsed = block.timestamp - firstObservation.timestamp; return timeElapsed; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function approve(address spender, uint tokens) external returns (bool success); function transfer(address to, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IUniswapOracle { function getPair() external view returns (address); function update() external; function getTimeElapsed(address tokenIn, address tokenOut) external view returns (uint); function consultAB(uint amountIn) external view returns (uint amountOut); function consultBA(uint amountIn) external view returns (uint amountOut); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IERC20.sol"; interface IUniswapV2ERC20 is IERC20 { function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import './FullMath.sol'; import './Babylonian.sol'; import './BitMath.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { return add(a, b, "SafeMath: Add Overflow"); } function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage);// "SafeMath: Add Overflow" return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: Underflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b;// "SafeMath: Underflow" return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b, "SafeMath: Mul Overflow"); } function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage);// "SafeMath: Mul Overflow" return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '../interfaces/IUniswapV2Pair.sol'; import "./SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'a7fea0ca09af3ad115eed91f6f5abeff5b69eb113dceedb234968ab0b2fe1216' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IUniswapV2Pair.sol"; import "./FixedPoint.sol"; library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } }
returns the index of the observation corresponding to the given timestamp
function observationIndexOf(uint timestamp) public view returns (uint8 index) { uint epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); }
109,615
[ 1, 6154, 326, 770, 434, 326, 13853, 4656, 358, 326, 864, 2858, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13853, 31985, 12, 11890, 2858, 13, 1071, 1476, 1135, 261, 11890, 28, 770, 13, 288, 203, 3639, 2254, 7632, 5027, 273, 2858, 342, 3879, 1225, 31, 203, 3639, 327, 2254, 28, 12, 12015, 5027, 738, 25380, 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 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/ISTFactory.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ISecurityTokenRegistry.sol"; import "./storage/EternalStorage.sol"; import "./libraries/Util.sol"; import "./libraries/Encoder.sol"; import "./libraries/VersionUtils.sol"; /** * @title Registry contract for issuers to register their tickers and security tokens */ contract SecurityTokenRegistry is ISecurityTokenRegistry, EternalStorage { /** * @notice state variables address public polyToken; uint256 public stLaunchFee; uint256 public tickerRegFee; uint256 public expiryLimit; uint256 public latestProtocolVersion; bool public paused; address public owner; address public polymathRegistry; address[] public activeUsers; mapping(address => bool) public seenUsers; mapping(address => bytes32[]) userToTickers; mapping(string => address) tickerToSecurityToken; mapping(string => uint) tickerIndex; mapping(string => TickerDetails) registeredTickers; mapping(address => SecurityTokenData) securityTokens; mapping(bytes32 => address) protocolVersionST; mapping(uint256 => ProtocolVersion) versionData; struct ProtocolVersion { uint8 major; uint8 minor; uint8 patch; } struct TickerDetails { address owner; uint256 registrationDate; uint256 expiryDate; string tokenName; bool status; } struct SecurityTokenData { string ticker; string tokenDetails; uint256 deployedAt; } */ using SafeMath for uint256; bytes32 constant INITIALIZE = 0x9ef7257c3339b099aacf96e55122ee78fb65a36bd2a6c19249882be9c98633bf; bytes32 constant POLYTOKEN = 0xacf8fbd51bb4b83ba426cdb12f63be74db97c412515797993d2a385542e311d7; bytes32 constant STLAUNCHFEE = 0xd677304bb45536bb7fdfa6b9e47a3c58fe413f9e8f01474b0a4b9c6e0275baf2; bytes32 constant TICKERREGFEE = 0x2fcc69711628630fb5a42566c68bd1092bc4aa26826736293969fddcd11cb2d2; bytes32 constant EXPIRYLIMIT = 0x604268e9a73dfd777dcecb8a614493dd65c638bad2f5e7d709d378bd2fb0baee; bytes32 constant PAUSED = 0xee35723ac350a69d2a92d3703f17439cbaadf2f093a21ba5bf5f1a53eb2a14d9; bytes32 constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; bytes32 constant POLYMATHREGISTRY = 0x90eeab7c36075577c7cc5ff366e389fefa8a18289b949bab3529ab4471139d4d; // Emit when network becomes paused event Pause(uint256 _timestammp); // Emit when network becomes unpaused event Unpause(uint256 _timestamp); // Emit when the ticker is removed from the registry event TickerRemoved(string _ticker, uint256 _removedAt, address _removedBy); // Emit when the token ticker expiry is changed event ChangeExpiryLimit(uint256 _oldExpiry, uint256 _newExpiry); // Emit when changeSecurityLaunchFee is called event ChangeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee); // Emit when changeTickerRegistrationFee is called event ChangeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee); // Emit when ownership gets transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Emit when ownership of the ticker gets changed event ChangeTickerOwnership(string _ticker, address indexed _oldOwner, address indexed _newOwner); // Emit at the time of launching a new security token event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _registrationFee ); // Emit after ticker registration event RegisterTicker( address indexed _owner, string _ticker, string _name, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFee ); ///////////////////////////// // Modifiers ///////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner(),"sender must be owner"); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPausedOrOwner() { if (msg.sender == owner()) _; else { require(!isPaused(), "Already paused"); _; } } /** * @notice Modifier to make a function callable only when the contract is not paused and ignore is msg.sender is owner. */ modifier whenNotPaused() { require(!isPaused(), "Already paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(isPaused(), "Should not be paused"); _; } ///////////////////////////// // Initialization ///////////////////////////// /** * @notice Initializes instance of STR * @param _polymathRegistry is the address of the Polymath Registry * @param _STFactory is the address of the Proxy contract for Security Tokens * @param _stLaunchFee is the fee in POLY required to launch a token * @param _tickerRegFee is the fee in POLY required to register a ticker * @param _polyToken is the address of the POLY ERC20 token * @param _owner is the owner of the STR */ function initialize( address _polymathRegistry, address _STFactory, uint256 _stLaunchFee, uint256 _tickerRegFee, address _polyToken, address _owner ) external payable { require(!getBool(INITIALIZE),"already initialized"); require( _STFactory != address(0) && _polyToken != address(0) && _owner != address(0) && _polymathRegistry != address(0), "Invalid address" ); require(_stLaunchFee != 0 && _tickerRegFee != 0, "Fees should not be 0"); set(POLYTOKEN, _polyToken); set(STLAUNCHFEE, _stLaunchFee); set(TICKERREGFEE, _tickerRegFee); set(EXPIRYLIMIT, uint256(60 * 1 days)); set(PAUSED, false); set(OWNER, _owner); set(POLYMATHREGISTRY, _polymathRegistry); _setProtocolVersion(_STFactory, uint8(2), uint8(0), uint8(0)); set(INITIALIZE, true); } ///////////////////////////// // Token Ticker Management ///////////////////////////// /** * @notice Registers the token ticker to the selected owner * @notice Once the token ticker is registered to its owner then no other issuer can claim * @notice its ownership. If the ticker expires and its issuer hasn't used it, then someone else can take it. * @param _owner is address of the owner of the token * @param _ticker is unique token ticker * @param _tokenName is the name of the token */ function registerTicker(address _owner, string _ticker, string _tokenName) external whenNotPausedOrOwner { require(_owner != address(0), "Owner should not be 0x"); require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Ticker length range (0,10]"); // Attempt to charge the reg fee if it is > 0 POLY uint256 tickerFee = getTickerRegistrationFee(); if (tickerFee > 0) require(IERC20(getAddress(POLYTOKEN)).transferFrom(msg.sender, address(this), tickerFee), "Insufficent allowance"); string memory ticker = Util.upper(_ticker); require(_tickerAvailable(ticker), "Ticker is reserved"); // Check whether ticker was previously registered (and expired) address previousOwner = _tickerOwner(ticker); if (previousOwner != address(0)) { _deleteTickerOwnership(previousOwner, ticker); } /*solium-disable-next-line security/no-block-members*/ _addTicker(_owner, ticker, _tokenName, now, now.add(getExpiryLimit()), false, false, tickerFee); } /** * @notice Internal - Sets the details of the ticker */ function _addTicker( address _owner, string _ticker, string _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status, bool _fromAdmin, uint256 _fee ) internal { _setTickerOwnership(_owner, _ticker); _storeTickerDetails(_ticker, _owner, _registrationDate, _expiryDate, _tokenName, _status); emit RegisterTicker(_owner, _ticker, _tokenName, _registrationDate, _expiryDate, _fromAdmin, _fee); } /** * @notice Modifies the ticker details. Only Polymath has the ability to do so. * @notice Only allowed to modify the tickers which are not yet deployed. * @param _owner is the owner of the token * @param _ticker is the token ticker * @param _tokenName is the name of the token * @param _registrationDate is the date at which ticker is registered * @param _expiryDate is the expiry date for the ticker * @param _status is the token deployment status */ function modifyTicker( address _owner, string _ticker, string _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) external onlyOwner { require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Ticker length range (0,10]"); require(_expiryDate != 0 && _registrationDate != 0, "Dates should not be 0"); require(_registrationDate <= _expiryDate, "Registration date should < expiry date"); require(_owner != address(0), "Invalid address"); string memory ticker = Util.upper(_ticker); _modifyTicker(_owner, ticker, _tokenName, _registrationDate, _expiryDate, _status); } /** * @notice Internal -- Modifies the ticker details. */ function _modifyTicker( address _owner, string _ticker, string _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { address currentOwner = _tickerOwner(_ticker); if (currentOwner != address(0)) { _deleteTickerOwnership(currentOwner, _ticker); } if (_tickerStatus(_ticker) && !_status) { set(Encoder.getKey("tickerToSecurityToken", _ticker), address(0)); } // If status is true, there must be a security token linked to the ticker already if (_status) { require(getAddress(Encoder.getKey("tickerToSecurityToken", _ticker)) != address(0), "Token not registered"); } _addTicker(_owner, _ticker, _tokenName, _registrationDate, _expiryDate, _status, true, uint256(0)); } function _tickerOwner(string _ticker) internal view returns(address) { return getAddress(Encoder.getKey("registeredTickers_owner", _ticker)); } /** * @notice Removes the ticker details, associated ownership & security token mapping * @param _ticker is the token ticker */ function removeTicker(string _ticker) external onlyOwner { string memory ticker = Util.upper(_ticker); address owner = _tickerOwner(ticker); require(owner != address(0), "Ticker doesn't exist"); _deleteTickerOwnership(owner, ticker); set(Encoder.getKey("tickerToSecurityToken", ticker), address(0)); _storeTickerDetails(ticker, address(0), 0, 0, "", false); /*solium-disable-next-line security/no-block-members*/ emit TickerRemoved(ticker, now, msg.sender); } /** * @notice Internal - Checks if the entered ticker is registered and has not expired * @param _ticker is the token ticker * @return bool */ function _tickerAvailable(string _ticker) internal view returns(bool) { if (_tickerOwner(_ticker) != address(0)) { /*solium-disable-next-line security/no-block-members*/ if ((now > getUint(Encoder.getKey("registeredTickers_expiryDate", _ticker))) && !_tickerStatus(_ticker)) { return true; } else return false; } return true; } function _tickerStatus(string _ticker) internal view returns(bool) { return getBool(Encoder.getKey("registeredTickers_status", _ticker)); } /** * @notice Internal - Sets the ticker owner * @param _owner is the address of the owner of the ticker * @param _ticker is the ticker symbol */ function _setTickerOwnership(address _owner, string _ticker) internal { bytes32 _ownerKey = Encoder.getKey("userToTickers", _owner); uint256 length = uint256(getArrayBytes32(_ownerKey).length); pushArray(_ownerKey, Util.stringToBytes32(_ticker)); set(Encoder.getKey("tickerIndex", _ticker), length); bytes32 seenKey = Encoder.getKey("seenUsers", _owner); if (!getBool(seenKey)) { pushArray(Encoder.getKey("activeUsers"), _owner); set(seenKey, true); } } /** * @notice Internal - Stores the ticker details */ function _storeTickerDetails( string _ticker, address _owner, uint256 _registrationDate, uint256 _expiryDate, string _tokenName, bool _status ) internal { bytes32 key = Encoder.getKey("registeredTickers_owner", _ticker); if (getAddress(key) != _owner) set(key, _owner); key = Encoder.getKey("registeredTickers_registrationDate", _ticker); if (getUint(key) != _registrationDate) set(key, _registrationDate); key = Encoder.getKey("registeredTickers_expiryDate", _ticker); if (getUint(key) != _expiryDate) set(key, _expiryDate); key = Encoder.getKey("registeredTickers_tokenName", _ticker); if (Encoder.getKey(getString(key)) != Encoder.getKey(_tokenName)) set(key, _tokenName); key = Encoder.getKey("registeredTickers_status", _ticker); if (getBool(key) != _status) set(key, _status); } /** * @notice Transfers the ownership of the ticker * @param _newOwner is the address of the new owner of the ticker * @param _ticker is the ticker symbol */ function transferTickerOwnership(address _newOwner, string _ticker) external whenNotPausedOrOwner { string memory ticker = Util.upper(_ticker); require(_newOwner != address(0), "Invalid address"); bytes32 ownerKey = Encoder.getKey("registeredTickers_owner", ticker); require(getAddress(ownerKey) == msg.sender, "Not authorised"); if (_tickerStatus(ticker)) require(IOwnable(getAddress(Encoder.getKey("tickerToSecurityToken", ticker))).owner() == _newOwner, "New owner does not match token owner"); _deleteTickerOwnership(msg.sender, ticker); _setTickerOwnership(_newOwner, ticker); set(ownerKey, _newOwner); emit ChangeTickerOwnership(ticker, msg.sender, _newOwner); } /** * @notice Internal - Removes the owner of a ticker */ function _deleteTickerOwnership(address _owner, string _ticker) internal { uint256 index = uint256(getUint(Encoder.getKey("tickerIndex", _ticker))); bytes32 ownerKey = Encoder.getKey("userToTickers", _owner); bytes32[] memory tickers = getArrayBytes32(ownerKey); assert(index < tickers.length); assert(_tickerOwner(_ticker) == _owner); deleteArrayBytes32(ownerKey, index); if (getArrayBytes32(ownerKey).length > index) { bytes32 switchedTicker = getArrayBytes32(ownerKey)[index]; set(Encoder.getKey("tickerIndex", Util.bytes32ToString(switchedTicker)), index); } } /** * @notice Changes the expiry time for the token ticker. Only available to Polymath. * @param _newExpiry is the new expiry for newly generated tickers */ function changeExpiryLimit(uint256 _newExpiry) external onlyOwner { require(_newExpiry >= 1 days, "Expiry should >= 1 day"); emit ChangeExpiryLimit(getUint(EXPIRYLIMIT), _newExpiry); set(EXPIRYLIMIT, _newExpiry); } /** * @notice Returns the list of tickers owned by the selected address * @param _owner is the address which owns the list of tickers */ function getTickersByOwner(address _owner) external view returns(bytes32[]) { uint counter = 0; // accessing the data structure userTotickers[_owner].length bytes32[] memory tickers = getArrayBytes32(Encoder.getKey("userToTickers", _owner)); for (uint i = 0; i < tickers.length; i++) { string memory ticker = Util.bytes32ToString(tickers[i]); /*solium-disable-next-line security/no-block-members*/ if (getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)) >= now || _tickerStatus(ticker)) { counter ++; } } bytes32[] memory tempList = new bytes32[](counter); counter = 0; for (i = 0; i < tickers.length; i++) { ticker = Util.bytes32ToString(tickers[i]); /*solium-disable-next-line security/no-block-members*/ if (getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)) >= now || _tickerStatus(ticker)) { tempList[counter] = tickers[i]; counter ++; } } return tempList; } /** * @notice Returns the list of tokens owned by the selected address * @param _owner is the address which owns the list of tickers * @dev Intention is that this is called off-chain so block gas limit is not relevant */ function getTokensByOwner(address _owner) external view returns(address[]) { // Loop over all active users, then all associated tickers of those users // This ensures we find tokens, even if their owner has been modified address[] memory activeUsers = getArrayAddress(Encoder.getKey("activeUsers")); bytes32[] memory tickers; address token; uint256 count = 0; uint256 i = 0; uint256 j = 0; for (i = 0; i < activeUsers.length; i++) { tickers = getArrayBytes32(Encoder.getKey("userToTickers", activeUsers[i])); for (j = 0; j < tickers.length; j++) { token = getAddress(Encoder.getKey("tickerToSecurityToken", Util.bytes32ToString(tickers[j]))); if (token != address(0)) { if (IOwnable(token).owner() == _owner) { count = count + 1; } } } } uint256 index = 0; address[] memory result = new address[](count); for (i = 0; i < activeUsers.length; i++) { tickers = getArrayBytes32(Encoder.getKey("userToTickers", activeUsers[i])); for (j = 0; j < tickers.length; j++) { token = getAddress(Encoder.getKey("tickerToSecurityToken", Util.bytes32ToString(tickers[j]))); if (token != address(0)) { if (IOwnable(token).owner() == _owner) { result[index] = token; index = index + 1; } } } } return result; } /** * @notice Returns the owner and timestamp for a given ticker * @param _ticker is the ticker symbol * @return address * @return uint256 * @return uint256 * @return string * @return bool */ function getTickerDetails(string _ticker) external view returns (address, uint256, uint256, string, bool) { string memory ticker = Util.upper(_ticker); bool tickerStatus = _tickerStatus(ticker); uint256 expiryDate = getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)); /*solium-disable-next-line security/no-block-members*/ if ((tickerStatus == true) || (expiryDate > now)) { return ( _tickerOwner(ticker), getUint(Encoder.getKey("registeredTickers_registrationDate", ticker)), expiryDate, getString(Encoder.getKey("registeredTickers_tokenName", ticker)), tickerStatus ); } else return (address(0), uint256(0), uint256(0), "", false); } ///////////////////////////// // Security Token Management ///////////////////////////// /** * @notice Deploys an instance of a new Security Token and records it to the registry * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function generateSecurityToken(string _name, string _ticker, string _tokenDetails, bool _divisible) external whenNotPausedOrOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Ticker length > 0"); string memory ticker = Util.upper(_ticker); bytes32 statusKey = Encoder.getKey("registeredTickers_status", ticker); require(!getBool(statusKey), "Already deployed"); set(statusKey, true); require(_tickerOwner(ticker) == msg.sender, "Not authorised"); /*solium-disable-next-line security/no-block-members*/ require(getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)) >= now, "Ticker gets expired"); uint256 launchFee = getSecurityTokenLaunchFee(); if (launchFee > 0) require(IERC20(getAddress(POLYTOKEN)).transferFrom(msg.sender, address(this), launchFee), "Insufficient allowance"); address newSecurityTokenAddress = ISTFactory(getSTFactoryAddress()).deployToken( _name, ticker, 18, _tokenDetails, msg.sender, _divisible, getAddress(POLYMATHREGISTRY) ); /*solium-disable-next-line security/no-block-members*/ _storeSecurityTokenData(newSecurityTokenAddress, ticker, _tokenDetails, now); set(Encoder.getKey("tickerToSecurityToken", ticker), newSecurityTokenAddress); /*solium-disable-next-line security/no-block-members*/ emit NewSecurityToken(ticker, _name, newSecurityTokenAddress, msg.sender, now, msg.sender, false, launchFee); } /** * @notice Adds a new custom Security Token and saves it to the registry. (Token should follow the ISecurityToken interface) * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _owner is the owner of the token * @param _securityToken is the address of the securityToken * @param _tokenDetails is the off-chain details of the token * @param _deployedAt is the timestamp at which the security token is deployed */ function modifySecurityToken( string _name, string _ticker, address _owner, address _securityToken, string _tokenDetails, uint256 _deployedAt ) external onlyOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "String length > 0"); require(bytes(_ticker).length <= 10, "Ticker length range (0,10]"); require(_deployedAt != 0 && _owner != address(0), "0 value params not allowed"); string memory ticker = Util.upper(_ticker); require(_securityToken != address(0), "ST address is 0x"); uint256 registrationTime = getUint(Encoder.getKey("registeredTickers_registrationDate", ticker)); uint256 expiryTime = getUint(Encoder.getKey("registeredTickers_expiryDate", ticker)); if (registrationTime == 0) { /*solium-disable-next-line security/no-block-members*/ registrationTime = now; expiryTime = registrationTime.add(getExpiryLimit()); } set(Encoder.getKey("tickerToSecurityToken", ticker), _securityToken); _modifyTicker(_owner, ticker, _name, registrationTime, expiryTime, true); _storeSecurityTokenData(_securityToken, ticker, _tokenDetails, _deployedAt); emit NewSecurityToken(ticker, _name, _securityToken, _owner, _deployedAt, msg.sender, true, getSecurityTokenLaunchFee()); } /** * @notice Internal - Stores the security token details */ function _storeSecurityTokenData(address _securityToken, string _ticker, string _tokenDetails, uint256 _deployedAt) internal { set(Encoder.getKey("securityTokens_ticker", _securityToken), _ticker); set(Encoder.getKey("securityTokens_tokenDetails", _securityToken), _tokenDetails); set(Encoder.getKey("securityTokens_deployedAt", _securityToken), _deployedAt); } /** * @notice Checks that Security Token is registered * @param _securityToken is the address of the security token * @return bool */ function isSecurityToken(address _securityToken) external view returns (bool) { return (keccak256(bytes(getString(Encoder.getKey("securityTokens_ticker", _securityToken)))) != keccak256("")); } /** * @notice Returns the security token address by ticker symbol * @param _ticker is the ticker of the security token * @return address */ function getSecurityTokenAddress(string _ticker) external view returns (address) { string memory ticker = Util.upper(_ticker); return getAddress(Encoder.getKey("tickerToSecurityToken", ticker)); } /** * @notice Returns the security token data by address * @param _securityToken is the address of the security token. * @return string is the ticker of the security Token. * @return address is the issuer of the security Token. * @return string is the details of the security token. * @return uint256 is the timestamp at which security Token was deployed. */ function getSecurityTokenData(address _securityToken) external view returns (string, address, string, uint256) { return ( getString(Encoder.getKey("securityTokens_ticker", _securityToken)), IOwnable(_securityToken).owner(), getString(Encoder.getKey("securityTokens_tokenDetails", _securityToken)), getUint(Encoder.getKey("securityTokens_deployedAt", _securityToken)) ); } ///////////////////////////// // Ownership, lifecycle & Utility ///////////////////////////// /** * @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) external onlyOwner { require(_newOwner != address(0), "Invalid address"); emit OwnershipTransferred(getAddress(OWNER), _newOwner); set(OWNER, _newOwner); } /** * @notice Called by the owner to pause, triggers stopped state */ function pause() external whenNotPaused onlyOwner { set(PAUSED, true); /*solium-disable-next-line security/no-block-members*/ emit Pause(now); } /** * @notice Called by the owner to unpause, returns to normal state */ function unpause() external whenPaused onlyOwner { set(PAUSED, false); /*solium-disable-next-line security/no-block-members*/ emit Unpause(now); } /** * @notice Sets the ticker registration fee in POLY tokens. Only Polymath. * @param _tickerRegFee is the registration fee in POLY tokens (base 18 decimals) */ function changeTickerRegistrationFee(uint256 _tickerRegFee) external onlyOwner { uint256 fee = getUint(TICKERREGFEE); require(fee != _tickerRegFee, "Fee not changed"); emit ChangeTickerRegistrationFee(fee, _tickerRegFee); set(TICKERREGFEE, _tickerRegFee); } /** * @notice Sets the ticker registration fee in POLY tokens. Only Polymath. * @param _stLaunchFee is the registration fee in POLY tokens (base 18 decimals) */ function changeSecurityLaunchFee(uint256 _stLaunchFee) external onlyOwner { uint256 fee = getUint(STLAUNCHFEE); require(fee != _stLaunchFee, "Fee not changed"); emit ChangeSecurityLaunchFee(fee, _stLaunchFee); set(STLAUNCHFEE, _stLaunchFee); } /** * @notice Reclaims all ERC20Basic compatible tokens * @param _tokenContract is the address of the token contract */ function reclaimERC20(address _tokenContract) external onlyOwner { require(_tokenContract != address(0), "Invalid address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance), "Transfer failed"); } /** * @notice Changes the protocol version and the SecurityToken contract * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _STFactoryAddress is the address of the proxy. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setProtocolVersion(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) external onlyOwner { require(_STFactoryAddress != address(0), "0x address is not allowed"); _setProtocolVersion(_STFactoryAddress, _major, _minor, _patch); } /** * @notice Internal - Changes the protocol version and the SecurityToken contract */ function _setProtocolVersion(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) internal { uint8[] memory _version = new uint8[](3); _version[0] = _major; _version[1] = _minor; _version[2] = _patch; uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(VersionUtils.isValidVersion(getProtocolVersion(), _version),"In-valid version"); set(Encoder.getKey("latestVersion"), uint256(_packedVersion)); set(Encoder.getKey("protocolVersionST", getUint(Encoder.getKey("latestVersion"))), _STFactoryAddress); } /** * @notice Returns the current STFactory Address */ function getSTFactoryAddress() public view returns(address) { return getAddress(Encoder.getKey("protocolVersionST", getUint(Encoder.getKey("latestVersion")))); } /** * @notice Gets Protocol version */ function getProtocolVersion() public view returns(uint8[]) { return VersionUtils.unpack(uint24(getUint(Encoder.getKey("latestVersion")))); } /** * @notice Changes the PolyToken address. Only Polymath. * @param _newAddress is the address of the polytoken. */ function updatePolyTokenAddress(address _newAddress) external onlyOwner { require(_newAddress != address(0), "Invalid address"); set(POLYTOKEN, _newAddress); } /** * @notice Gets the security token launch fee * @return Fee amount */ function getSecurityTokenLaunchFee() public view returns(uint256) { return getUint(STLAUNCHFEE); } /** * @notice Gets the ticker registration fee * @return Fee amount */ function getTickerRegistrationFee() public view returns(uint256) { return getUint(TICKERREGFEE); } /** * @notice Gets the expiry limit * @return Expiry limit */ function getExpiryLimit() public view returns(uint256) { return getUint(EXPIRYLIMIT); } /** * @notice Check whether the registry is paused or not * @return bool */ function isPaused() public view returns(bool) { return getBool(PAUSED); } /** * @notice Gets the owner of the contract * @return address owner */ function owner() public view returns(address) { return getAddress(OWNER); } }
* @notice Internal - Checks if the entered ticker is registered and has not expired @param _ticker is the token ticker @return bool/solium-disable-next-line security/no-block-members*/
function _tickerAvailable(string _ticker) internal view returns(bool) { if (_tickerOwner(_ticker) != address(0)) { if ((now > getUint(Encoder.getKey("registeredTickers_expiryDate", _ticker))) && !_tickerStatus(_ticker)) { return true; } else return false; } return true; }
12,831,539
[ 1, 3061, 300, 13074, 309, 326, 16219, 14063, 353, 4104, 471, 711, 486, 7708, 225, 389, 88, 5448, 353, 326, 1147, 14063, 327, 1426, 19, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 2629, 17, 7640, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 88, 5448, 5268, 12, 1080, 389, 88, 5448, 13, 2713, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 309, 261, 67, 88, 5448, 5541, 24899, 88, 5448, 13, 480, 1758, 12, 20, 3719, 288, 203, 5411, 309, 14015, 3338, 405, 336, 5487, 12, 7204, 18, 588, 653, 2932, 14327, 6264, 414, 67, 22409, 1626, 3113, 389, 88, 5448, 20349, 597, 401, 67, 88, 5448, 1482, 24899, 88, 5448, 3719, 288, 203, 7734, 327, 638, 31, 203, 5411, 289, 469, 203, 7734, 327, 629, 31, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x41b98Df01000BD7EBb6d91c333C73c68e6CeBFC9/sources/src/automation/gelato/BackCombatibleTransfer.sol
@notice Library that adding support for ERC20 and native tokens transfers. @dev Based of https://github.com/gelatodigital/ops/blob/9a9cde6ab2f1b132b949f9244fd59a1de4da4123/contracts/vendor/gelato/FGelato.sol
library BackCombatibleTransfer { address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function backCombatibleTransfer( address payable to, address paymentToken, uint256 amount pragma solidity ^0.8.19; import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; ) internal { if (paymentToken == ETH) { safeNativeTransfer(to, amount); return; } SafeERC20.safeTransfer(IERC20(paymentToken), to, amount); } ) internal { if (paymentToken == ETH) { safeNativeTransfer(to, amount); return; } SafeERC20.safeTransfer(IERC20(paymentToken), to, amount); } function safeNativeTransfer(address payable to, uint256 amount) internal { require(success, "Native transfer failed"); } (bool success, ) = to.call{value: amount}(""); }
11,039,925
[ 1, 9313, 716, 6534, 2865, 364, 4232, 39, 3462, 471, 6448, 2430, 29375, 18, 225, 25935, 434, 2333, 2207, 6662, 18, 832, 19, 75, 292, 270, 369, 360, 7053, 19, 4473, 19, 10721, 19, 29, 69, 29, 71, 323, 26, 378, 22, 74, 21, 70, 22152, 70, 29, 7616, 74, 29, 3247, 24, 8313, 6162, 69, 21, 323, 24, 2414, 24, 12936, 19, 16351, 87, 19, 10645, 19, 75, 292, 31093, 19, 42, 43, 292, 31093, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4297, 11328, 8161, 5912, 288, 203, 565, 1758, 1071, 5381, 512, 2455, 273, 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, 445, 1473, 11328, 8161, 5912, 12, 203, 3639, 1758, 8843, 429, 358, 16, 203, 3639, 1758, 5184, 1345, 16, 203, 3639, 2254, 5034, 3844, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 3657, 31, 203, 5666, 288, 9890, 654, 39, 3462, 16, 467, 654, 39, 3462, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 5471, 19, 9890, 654, 39, 3462, 18, 18281, 14432, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 9261, 1345, 422, 512, 2455, 13, 288, 203, 5411, 4183, 9220, 5912, 12, 869, 16, 3844, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 14060, 654, 39, 3462, 18, 4626, 5912, 12, 45, 654, 39, 3462, 12, 9261, 1345, 3631, 358, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 262, 2713, 288, 203, 3639, 309, 261, 9261, 1345, 422, 512, 2455, 13, 288, 203, 5411, 4183, 9220, 5912, 12, 869, 16, 3844, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 14060, 654, 39, 3462, 18, 4626, 5912, 12, 45, 654, 39, 3462, 12, 9261, 1345, 3631, 358, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 4183, 9220, 5912, 12, 2867, 8843, 429, 358, 2 ]
./partial_match/42/0x05722b2C4dd21770ac8c6a8077ADA0828266672f/sources/Implementation.sol
0-a. Pay out to Pool
mintToPool(poolReward);
3,297,523
[ 1, 20, 17, 69, 18, 13838, 596, 358, 8828, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6647, 312, 474, 774, 2864, 12, 6011, 17631, 1060, 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/3/0x19E860E37082a6932D29Fd184076F3Ba43F23259/sources/ItemBase.sol
* @dev Same with constructor, but is used and called by storage proxy as logic contract./ trick test
function getMetaInfo(uint256 _index) external view returns ( uint16, uint16, uint16, uint128 ); @dev returns the minor addresses of the formula. 0x762b8a4d function getMajorAddresses(uint256 _index) external view returns (address[] memory); @dev returns canDisenchant of the formula. function getDisenchant(uint256 _index) external view returns (bool); } } } } function initialize(address _registry) public initializer { owner = msg.sender; emit LogSetOwner(msg.sender); registry = ISettingsRegistry(_registry); lastItemObjectId = 2000; }
5,141,176
[ 1, 8650, 598, 3885, 16, 1496, 353, 1399, 471, 2566, 635, 2502, 2889, 487, 4058, 6835, 18, 19, 28837, 1842, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 11312, 966, 12, 11890, 5034, 389, 1615, 13, 203, 202, 202, 9375, 203, 202, 202, 1945, 203, 202, 202, 6154, 261, 203, 1082, 202, 11890, 2313, 16, 203, 1082, 202, 11890, 2313, 16, 203, 1082, 202, 11890, 2313, 16, 203, 1082, 202, 11890, 10392, 203, 202, 202, 1769, 203, 203, 3639, 632, 5206, 1135, 326, 8439, 6138, 434, 326, 8013, 18, 203, 1082, 377, 374, 92, 6669, 22, 70, 28, 69, 24, 72, 203, 202, 915, 2108, 6284, 7148, 12, 11890, 5034, 389, 1615, 13, 203, 202, 202, 9375, 203, 202, 202, 1945, 203, 202, 202, 6154, 261, 2867, 8526, 3778, 1769, 203, 203, 3639, 632, 5206, 1135, 848, 1669, 7382, 970, 434, 326, 8013, 18, 203, 202, 915, 336, 1669, 7382, 970, 12, 11890, 5034, 389, 1615, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 97, 203, 203, 203, 97, 203, 203, 203, 97, 203, 203, 203, 97, 203, 203, 203, 203, 202, 915, 4046, 12, 2867, 389, 9893, 13, 1071, 12562, 288, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 202, 18356, 1827, 694, 5541, 12, 3576, 18, 15330, 1769, 203, 202, 202, 9893, 273, 467, 2628, 4243, 24899, 9893, 1769, 203, 203, 202, 202, 2722, 1180, 16661, 273, 16291, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // @openzeppelin/[email protected] interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } // Generator is the Miner of AF. He can make AF and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once AF is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Generator is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAFPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAFPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. AFs to distribute per block. uint256 lastRewardBlock; // Last block number that AFs distribution occurs. uint256 accAFPerShare; // Accumulated AFs per share, times 1e12. See below. } // The AF TOKEN! IERC20 public tokenAF; // total mint amount. uint256 public mintReward; uint public constant SUSPEND_MINING_BALANCE = 100000e8; // Dev address. address public devaddr; // Block number when bonus AF period ends. uint256 public bonusEndBlock; // AF tokens created per block. uint256 public tokenAFPerBlock; // Bonus muliplier for early AF makers. uint256 public constant BONUS_MULTIPLIER = 5; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when AF mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Mint(address indexed to, uint256 amount); constructor( IERC20 _tokenAF, address _devaddr, uint256 _tokenAFPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { tokenAF = _tokenAF; devaddr = _devaddr; tokenAFPerBlock = _tokenAFPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAFPerShare: 0 })); } // Update the given pool's AF allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Migrate AF token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrateAF() public { require(address(migrator) != address(0), "migrate: no migrator token"); uint256 bal = tokenAF.balanceOf(address(this)); tokenAF.safeApprove(address(migrator), bal); IERC20 newToken = migrator.migrate(tokenAF); require(bal == newToken.balanceOf(address(this)), "migrate: bad"); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (tokenAF.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) { return 0; } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending AFs on frontend. function pendingAF(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAFPerShare = pool.accAFPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAFPerShare = accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAFPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mint(devaddr, tokenAFReward.div(10)); mintReward.add(tokenAFReward); pool.accAFPerShare = pool.accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Generator for AF rewards. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAFTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Generator. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAFTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe AF transfer function, just in case if rounding error causes pool to not have enough AFs. function safeAFTransfer(address _to, uint256 _amount) internal { uint256 AFBal = tokenAF.balanceOf(address(this)); if (_amount > AFBal) { tokenAF.transfer(_to, AFBal); } else { tokenAF.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function mint(address to, uint256 rewardAmount) private { if (rewardAmount == 0) { emit Mint(to, 0); return; } require(tokenAF.transfer(to, rewardAmount), 'Generator: transfer out of unlocked pool failed'); emit Mint(to, rewardAmount); } }
AF tokens created per block.
uint256 public tokenAFPerBlock;
5,438,309
[ 1, 6799, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1147, 6799, 2173, 1768, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV14Interface { event TRADE504( //inject NONSTANDARD NAMING address account, address suppliedAsset, address receivedAsset, address retainedAsset, uint256 suppliedAmount, uint256 recievedAmount, uint256 retainedAmount ); event ROLEMODIFIED267(Role indexed role, address account); //inject NONSTANDARD NAMING event ROLEPAUSED190(Role indexed role); //inject NONSTANDARD NAMING event ROLEUNPAUSED454(Role indexed role); //inject NONSTANDARD NAMING event ETHERRECEIVED220(address sender, uint256 amount); //inject NONSTANDARD NAMING event GASRESERVEREFILLED158(uint256 etherAmount); //inject NONSTANDARD NAMING enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER, // 4 GAS_RESERVE_REFILLER // 5 } enum TradeType { DAI_TO_TOKEN, DAI_TO_ETH, ETH_TO_DAI, TOKEN_TO_DAI, ETH_TO_TOKEN, TOKEN_TO_ETH, TOKEN_TO_TOKEN } struct RoleStatus { address account; bool paused; } function TRADEDAIFORETHERV2941( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAIV2888( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function TRADEDAIFORTOKEN895( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAI139( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought); function TRADETOKENFORETHER779( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function TRADEETHERFORTOKEN640( //inject NONSTANDARD NAMING address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold); function TRADEETHERFORTOKENUSINGETHERIZER777( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function TRADETOKENFORTOKEN271( //inject NONSTANDARD NAMING ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function TRADETOKENFORTOKENUSINGRESERVES584( //inject NONSTANDARD NAMING ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function TRADEDAIFORETHERUSINGRESERVESV2260( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV2493( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADEDAIFORTOKENUSINGRESERVES81( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI350( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADETOKENFORETHERUSINGRESERVES547( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function TRADEETHERFORTOKENUSINGRESERVES877( //inject NONSTANDARD NAMING address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function FINALIZEETHERDEPOSIT986( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function FINALIZEDAIDEPOSIT934( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function FINALIZEDHARMADAIDEPOSIT513( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function MINT202(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING function REDEEM16(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING function TRADEDDAIFORUSDC654( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function TRADEUSDCFORDDAI12( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function REFILLGASRESERVE448(uint256 etherAmount) external; //inject NONSTANDARD NAMING function WITHDRAWUSDC439(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAI337(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDHARMADAI28(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWUSDCTOPRIMARYRECIPIENT2(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAITOPRIMARYRECIPIENT618(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWETHER691( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external; function WITHDRAW743( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function CALLANY310( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function SETDAILIMIT40(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETETHERLIMIT732(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETPRIMARYUSDCRECIPIENT254(address recipient) external; //inject NONSTANDARD NAMING function SETPRIMARYDAIRECIPIENT844(address recipient) external; //inject NONSTANDARD NAMING function SETROLE668(Role role, address account) external; //inject NONSTANDARD NAMING function REMOVEROLE431(Role role) external; //inject NONSTANDARD NAMING function PAUSE546(Role role) external; //inject NONSTANDARD NAMING function UNPAUSE892(Role role) external; //inject NONSTANDARD NAMING function ISPAUSED688(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING function ISROLE537(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING function ISDHARMASMARTWALLET489( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function GETDEPOSITMANAGER179() external view returns (address depositManager); //inject NONSTANDARD NAMING function GETADJUSTER264() external view returns (address adjuster); //inject NONSTANDARD NAMING function GETRESERVETRADER364() external view returns (address reserveTrader); //inject NONSTANDARD NAMING function GETWITHDRAWALMANAGER637() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING function GETPAUSER909() external view returns (address pauser); //inject NONSTANDARD NAMING function GETGASRESERVEREFILLER909() external view returns (address gasReserveRefiller); //inject NONSTANDARD NAMING function GETRESERVES500() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function GETDAILIMIT177() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ); function GETETHERLIMIT782() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING function GETPRIMARYUSDCRECIPIENT773() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETPRIMARYDAIRECIPIENT581() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETIMPLEMENTATION743() external view returns (address implementation); //inject NONSTANDARD NAMING function GETINSTANCE306() external pure returns (address instance); //inject NONSTANDARD NAMING function GETVERSION428() external view returns (uint256 version); //inject NONSTANDARD NAMING } interface ERC20Interface { function BALANCEOF7(address) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE806(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE503(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER250(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM572(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING } interface DTokenInterface { function MINT202(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING function REDEEM16(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING function REDEEMUNDERLYING444(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING function BALANCEOF7(address) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING522(address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER250(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function APPROVE806(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function EXCHANGERATECURRENT321() external view returns (uint256); //inject NONSTANDARD NAMING } interface TradeHelperInterface { function TRADEUSDCFORDDAI12( //inject NONSTANDARD NAMING uint256 amountUSDC, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function TRADEDDAIFORUSDC654( //inject NONSTANDARD NAMING uint256 amountDai, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function GETEXPECTEDDAI546(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING function GETEXPECTEDUSDC60(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING } interface UniswapV2Interface { function SWAPTOKENSFOREXACTTOKENS381( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORTOKENS55( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORETH928( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPTOKENSFOREXACTETH806( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS164( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS988( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface EtherReceiverInterface { function SETTLEETHER224() external; //inject NONSTANDARD NAMING } library SafeMath { function ADD577(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB328(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function MUL983(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 DIV568(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, "SafeMath: division by zero"); return a / b; } } contract TwoStepOwnable { event OWNERSHIPTRANSFERRED746( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; function TRANSFEROWNERSHIP314(address newOwner) external ONLYOWNER349 { //inject NONSTANDARD NAMING require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } function CANCELOWNERSHIPTRANSFER449() external ONLYOWNER349 { //inject NONSTANDARD NAMING delete _newPotentialOwner; } function ACCEPTOWNERSHIP100() external { //inject NONSTANDARD NAMING require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OWNERSHIPTRANSFERRED746(_owner, msg.sender); _owner = msg.sender; } function OWNER217() external view returns (address) { //inject NONSTANDARD NAMING return _owner; } function ISOWNER119() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } modifier ONLYOWNER349() { //inject NONSTANDARD NAMING require(ISOWNER119(), "TwoStepOwnable: caller is not the owner."); _; } } contract DharmaTradeReserveV14ImplementationStaging is DharmaTradeReserveV14Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _version68 = 1014; //inject NONSTANDARD NAMING // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _usdc291 = ERC20Interface( //inject NONSTANDARD NAMING 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _dai607 = ERC20Interface( //inject NONSTANDARD NAMING 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _etherizer675 = ERC20Interface( //inject NONSTANDARD NAMING 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); DTokenInterface internal constant _ddai635 = DTokenInterface( //inject NONSTANDARD NAMING 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _trade_helper419 = TradeHelperInterface( //inject NONSTANDARD NAMING 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV2Interface internal constant _uniswap_router857 = UniswapV2Interface( //inject NONSTANDARD NAMING 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); EtherReceiverInterface internal constant _eth_receiver286 = EtherReceiverInterface( //inject NONSTANDARD NAMING 0xaf84687D21736F5E06f738c6F065e88890465E7c ); address internal constant _weth890 = address( //inject NONSTANDARD NAMING 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); address internal constant _gas_reserve614 = address( //inject NONSTANDARD NAMING 0x09cd826D4ABA4088E1381A1957962C946520952d // staging version ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _create2_header144 = bytes21( //inject NONSTANDARD NAMING 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _wallet_creation_code_header349 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING bytes28 internal constant _wallet_creation_code_footer225 = bytes28( //inject NONSTANDARD NAMING 0x00000000000000000000000000000000000000000000000000000000 ); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit ETHERRECEIVED220(msg.sender, msg.value); } function TRADEDAIFORETHERV2941( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN55(_dai607, msg.sender, daiAmount); // Trade Dai for Ether. totalDaiSold = _TRADEDAIFORETHER930( daiAmount, quotedEtherAmount, deadline, false ); } function TRADETOKENFORETHER779( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought) { // Transfer the tokens from the caller and revert on failure. _TRANSFERINTOKEN55(token, msg.sender, tokenAmount); // Trade tokens for Ether. totalEtherBought = _TRADETOKENFORETHER585( token, tokenAmount, quotedEtherAmount, deadline, false ); // Transfer the quoted Ether amount to the caller. _TRANSFERETHER189(msg.sender, quotedEtherAmount); } function TRADEDAIFORTOKEN895( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN55(_dai607, msg.sender, daiAmount); // Trade Dai for specified token. totalDaiSold = _TRADEDAIFORTOKEN293( token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false ); } function TRADEDAIFORETHERUSINGRESERVESV2260( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _REDEEMDDAIIFNECESSARY474(daiAmountFromReserves); // Trade Dai for Ether using reserves. totalDaiSold = _TRADEDAIFORETHER930( daiAmountFromReserves, quotedEtherAmount, deadline, true ); } function TRADETOKENFORETHERUSINGRESERVES547( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { // Trade tokens for Ether using reserves. totalEtherBought = _TRADETOKENFORETHER585( token, tokenAmountFromReserves, quotedEtherAmount, deadline, true ); } function TRADEETHERFORDAIV2888( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade Ether for Dai. totalDaiBought = _TRADEETHERFORDAI152( msg.value, quotedDaiAmount, deadline, false ); // Transfer the Dai to the caller and revert on failure. _TRANSFERTOKEN426(_dai607, msg.sender, quotedDaiAmount); } function TRADEETHERFORTOKEN640( //inject NONSTANDARD NAMING address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold) { // Trade Ether for the specified token. totalEtherSold = _TRADEETHERFORTOKEN294( token, msg.value, quotedTokenAmount, deadline, false ); } function TRADEETHERFORTOKENUSINGETHERIZER777( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold) { // Transfer the Ether from the caller and revert on failure. _TRANSFERINTOKEN55(_etherizer675, msg.sender, etherAmount); // Trade Ether for the specified token. totalEtherSold = _TRADEETHERFORTOKEN294( token, etherAmount, quotedTokenAmount, deadline, false ); } function TRADETOKENFORDAI139( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. _TRANSFERINTOKEN55(token, msg.sender, tokenAmount); // Trade the token for Dai. totalDaiBought = _TRADETOKENFORDAI325( token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false ); // Transfer the quoted Dai amount to the caller and revert on failure. _TRANSFERTOKEN426(_dai607, msg.sender, quotedDaiAmount); } function TRADETOKENFORTOKEN271( //inject NONSTANDARD NAMING ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold) { // Transfer the token from the caller and revert on failure. _TRANSFERINTOKEN55(tokenProvided, msg.sender, tokenProvidedAmount); totalTokensSold = _TRADETOKENFORTOKEN365( msg.sender, tokenProvided, tokenReceived, tokenProvidedAmount, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function TRADETOKENFORTOKENUSINGRESERVES584( //inject NONSTANDARD NAMING ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalTokensSold) { totalTokensSold = _TRADETOKENFORTOKEN365( address(this), tokenProvidedFromReserves, tokenReceived, tokenProvidedAmountFromReserves, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV2493( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade Ether for Dai using reserves. totalDaiBought = _TRADEETHERFORDAI152( etherAmountFromReserves, quotedDaiAmount, deadline, true ); // Mint dDai using the received Dai. totalDDaiMinted = _ddai635.MINT202(totalDaiBought); } function TRADEETHERFORTOKENUSINGRESERVES877( //inject NONSTANDARD NAMING address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) { // Trade Ether for token using reserves. totalEtherSold = _TRADEETHERFORTOKEN294( token, etherAmountFromReserves, quotedTokenAmount, deadline, true ); } function TRADEDAIFORTOKENUSINGRESERVES81( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _REDEEMDDAIIFNECESSARY474(daiAmountFromReserves); // Trade Dai for token using reserves. totalDaiSold = _TRADEDAIFORTOKEN293( token, daiAmountFromReserves, quotedTokenAmount, deadline, routeThroughEther, true ); } function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI350( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the token for Dai using reserves. totalDaiBought = _TRADETOKENFORDAI325( token, tokenAmountFromReserves, quotedDaiAmount, deadline, routeThroughEther, true ); // Mint dDai using the received Dai. totalDDaiMinted = _ddai635.MINT202(totalDaiBought); } function FINALIZEDAIDEPOSIT934( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external ONLYOWNEROR375(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET467(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. _TRANSFERTOKEN426(_dai607, smartWallet, daiAmount); } function FINALIZEDHARMADAIDEPOSIT513( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external ONLYOWNEROR375(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET467(smartWallet, initialUserSigningKey); // Get the current dDai exchange rate. uint256 exchangeRate = _ddai635.EXCHANGERATECURRENT321(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.MUL983(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. _TRANSFERTOKEN426(ERC20Interface(address(_ddai635)), smartWallet, dDaiAmount); } function FINALIZEETHERDEPOSIT986( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external ONLYOWNEROR375(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET467(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. _TRANSFERETHER189(smartWallet, etherAmount); } function MINT202( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _ddai635.MINT202(daiAmount); } function REDEEM16( //inject NONSTANDARD NAMING uint256 dDaiAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _ddai635.REDEEM16(dDaiAmount); } function TRADEUSDCFORDDAI12( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _trade_helper419.TRADEUSDCFORDDAI12( usdcAmount, quotedDaiEquivalentAmount ); } function TRADEDDAIFORUSDC654( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _trade_helper419.TRADEDDAIFORUSDC654( daiEquivalentAmount, quotedUSDCAmount ); } function REFILLGASRESERVE448(uint256 etherAmount) external ONLYOWNEROR375(Role.GAS_RESERVE_REFILLER) { //inject NONSTANDARD NAMING // Transfer the Ether to the gas reserve. _TRANSFERETHER189(_gas_reserve614, etherAmount); emit GASRESERVEREFILLED158(etherAmount); } function WITHDRAWUSDCTOPRIMARYRECIPIENT2( //inject NONSTANDARD NAMING uint256 usdcAmount ) external ONLYOWNEROR375(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. _TRANSFERTOKEN426(_usdc291, primaryRecipient, usdcAmount); } function WITHDRAWDAITOPRIMARYRECIPIENT618( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR375(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. _TRANSFERTOKEN426(_dai607, primaryRecipient, daiAmount); } function WITHDRAWUSDC439( //inject NONSTANDARD NAMING address recipient, uint256 usdcAmount ) external ONLYOWNER349 { // Transfer the USDC to the specified recipient. _TRANSFERTOKEN426(_usdc291, recipient, usdcAmount); } function WITHDRAWDAI337( //inject NONSTANDARD NAMING address recipient, uint256 daiAmount ) external ONLYOWNER349 { // Transfer the Dai to the specified recipient. _TRANSFERTOKEN426(_dai607, recipient, daiAmount); } function WITHDRAWDHARMADAI28( //inject NONSTANDARD NAMING address recipient, uint256 dDaiAmount ) external ONLYOWNER349 { // Transfer the dDai to the specified recipient. _TRANSFERTOKEN426(ERC20Interface(address(_ddai635)), recipient, dDaiAmount); } function WITHDRAWETHER691( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external ONLYOWNER349 { // Transfer the Ether to the specified recipient. _TRANSFERETHER189(recipient, etherAmount); } function WITHDRAW743( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external ONLYOWNER349 returns (bool success) { // Transfer the token to the specified recipient. success = token.TRANSFER250(recipient, amount); } function CALLANY310( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external ONLYOWNER349 returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } function SETDAILIMIT40(uint256 daiAmount) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new limit. _daiLimit = daiAmount; } function SETETHERLIMIT732(uint256 etherAmount) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new limit. _etherLimit = etherAmount; } function SETPRIMARYUSDCRECIPIENT254(address recipient) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryUSDCRecipient = recipient; } function SETPRIMARYDAIRECIPIENT844(address recipient) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryDaiRecipient = recipient; } function PAUSE546(Role role) external ONLYOWNEROR375(Role.PAUSER) { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit ROLEPAUSED190(role); } function UNPAUSE892(Role role) external ONLYOWNER349 { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit ROLEUNPAUSED454(role); } function SETROLE668(Role role, address account) external ONLYOWNER349 { //inject NONSTANDARD NAMING require(account != address(0), "Must supply an account."); _SETROLE96(role, account); } function REMOVEROLE431(Role role) external ONLYOWNER349 { //inject NONSTANDARD NAMING _SETROLE96(role, address(0)); } function ISPAUSED688(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING paused = _ISPAUSED235(role); } function ISROLE537(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = _ISROLE773(role); } function ISDHARMASMARTWALLET489( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _ISSMARTWALLET673(smartWallet, initialUserSigningKey); } function GETDEPOSITMANAGER179() external view returns (address depositManager) { //inject NONSTANDARD NAMING depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } function GETADJUSTER264() external view returns (address adjuster) { //inject NONSTANDARD NAMING adjuster = _roles[uint256(Role.ADJUSTER)].account; } function GETRESERVETRADER364() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } function GETWITHDRAWALMANAGER637() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } function GETPAUSER909() external view returns (address pauser) { //inject NONSTANDARD NAMING pauser = _roles[uint256(Role.PAUSER)].account; } function GETGASRESERVEREFILLER909() external view returns (address gasReserveRefiller) { //inject NONSTANDARD NAMING gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account; } function GETRESERVES500() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _dai607.BALANCEOF7(address(this)); dDai = _ddai635.BALANCEOF7(address(this)); dDaiUnderlying = _ddai635.BALANCEOFUNDERLYING522(address(this)); } function GETDAILIMIT177() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.MUL983(1e18)).DIV568(_ddai635.EXCHANGERATECURRENT321()); } function GETETHERLIMIT782() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING etherAmount = _etherLimit; } function GETPRIMARYUSDCRECIPIENT773() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryUSDCRecipient; } function GETPRIMARYDAIRECIPIENT581() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryDaiRecipient; } function GETIMPLEMENTATION743() external view returns ( //inject NONSTANDARD NAMING address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } function GETINSTANCE306() external pure returns (address instance) { //inject NONSTANDARD NAMING instance = address(0x09cd826D4ABA4088E1381A1957962C946520952d); } function GETVERSION428() external view returns (uint256 version) { //inject NONSTANDARD NAMING version = _version68; } function _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(ERC20Interface token, uint256 amount) internal { //inject NONSTANDARD NAMING if (token.ALLOWANCE503(address(this), address(_uniswap_router857)) < amount) { // Try removing approval for Uniswap router first as a workaround for unusual tokens. (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), uint256(0) ) ); // Grant approval for Uniswap router to transfer tokens on behalf of this contract. (success, data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), uint256(-1) ) ); if (!success) { // Some really janky tokens only allow setting approval up to current balance. (success, data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), amount ) ); } require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." ); } } function _TRADEETHERFORDAI152( //inject NONSTANDARD NAMING uint256 etherAmount, uint256 quotedDaiAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( _weth890, address(_dai607), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _uniswap_router857.SWAPEXACTETHFORTOKENS988.value(etherAmount)( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; _FIRETRADEEVENT684( fromReserves, TradeType.ETH_TO_DAI, address(0), etherAmount, quotedDaiAmount, totalDaiBought.SUB328(quotedDaiAmount) ); } function _TRADEDAIFORETHER930( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(_dai607), _weth890, false ); // Trade Dai for quoted Ether amount on Uniswap (send to appropriate recipient). amounts = _uniswap_router857.SWAPTOKENSFOREXACTETH806( quotedEtherAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _FIRETRADEEVENT684( fromReserves, TradeType.DAI_TO_ETH, address(0), daiAmount, quotedEtherAmount, daiAmount.SUB328(totalDaiSold) ); } function _TRADEETHERFORTOKEN294( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherSold) { // Establish path from Ether to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( _weth890, address(token), false ); // Trade Ether for quoted token amount on Uniswap and send to appropriate recipient. amounts = _uniswap_router857.SWAPETHFOREXACTTOKENS164.value(etherAmount)( quotedTokenAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalEtherSold = amounts[0]; _FIRETRADEEVENT684( fromReserves, TradeType.ETH_TO_TOKEN, address(token), etherAmount, quotedTokenAmount, etherAmount.SUB328(totalEtherSold) ); } function _TRADETOKENFORETHER585( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(token, tokenAmount); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(token), _weth890, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _uniswap_router857.SWAPEXACTTOKENSFORETH928( tokenAmount, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; _FIRETRADEEVENT684( fromReserves, TradeType.TOKEN_TO_ETH, address(token), tokenAmount, quotedEtherAmount, totalEtherBought.SUB328(quotedEtherAmount) ); } function _TRADEDAIFORTOKEN293( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(_dai607), address(token), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to appropriate recipient. amounts = _uniswap_router857.SWAPTOKENSFOREXACTTOKENS381( quotedTokenAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _FIRETRADEEVENT684( fromReserves, TradeType.DAI_TO_TOKEN, address(token), daiAmount, quotedTokenAmount, daiAmount.SUB328(totalDaiSold) ); } function _TRADETOKENFORDAI325( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(token, tokenAmount); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(token), address(_dai607), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap (send to this contract). amounts = _uniswap_router857.SWAPEXACTTOKENSFORTOKENS55( tokenAmount, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[path.length - 1]; _FIRETRADEEVENT684( fromReserves, TradeType.TOKEN_TO_DAI, address(token), tokenAmount, quotedDaiAmount, totalDaiBought.SUB328(quotedDaiAmount) ); } function _TRADETOKENFORTOKEN365( //inject NONSTANDARD NAMING address recipient, ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) internal returns (uint256 totalTokensSold) { uint256 retainedAmount; // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(tokenProvided, tokenProvidedAmount); if (routeThroughEther == false) { // Establish direct path between tokens. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(tokenProvided), tokenReceived, false ); // Trade for the quoted token amount on Uniswap and send to recipient. amounts = _uniswap_router857.SWAPTOKENSFOREXACTTOKENS381( quotedTokenReceivedAmount, tokenProvidedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = tokenProvidedAmount.SUB328(totalTokensSold); } else { // Establish path between provided token and WETH. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(tokenProvided), _weth890, false ); // Trade all provided tokens for WETH on Uniswap and send to this contract. amounts = _uniswap_router857.SWAPEXACTTOKENSFORTOKENS55( tokenProvidedAmount, 0, path, address(this), deadline ); retainedAmount = amounts[1]; // Establish path between WETH and received token. (path, amounts) = _CREATEPATHANDAMOUNTS240( _weth890, tokenReceived, false ); // Trade bought WETH for received token on Uniswap and send to recipient. amounts = _uniswap_router857.SWAPTOKENSFOREXACTTOKENS381( quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = retainedAmount.SUB328(totalTokensSold); } emit TRADE504( recipient, address(tokenProvided), tokenReceived, routeThroughEther ? _weth890 : address(tokenProvided), tokenProvidedAmount, quotedTokenReceivedAmount, retainedAmount ); } function _SETROLE96(Role role, address account) internal { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit ROLEMODIFIED267(role, account); } } function _FIRETRADEEVENT684( //inject NONSTANDARD NAMING bool fromReserves, TradeType tradeType, address token, uint256 suppliedAmount, uint256 receivedAmount, uint256 retainedAmount ) internal { uint256 t = uint256(tradeType); emit TRADE504( fromReserves ? address(this) : msg.sender, t < 2 ? address(_dai607) : (t % 2 == 0 ? address(0) : token), (t > 1 && t < 4) ? address(_dai607) : (t % 2 == 0 ? token : address(0)), t < 4 ? address(_dai607) : address(0), suppliedAmount, receivedAmount, retainedAmount ); } function _ISROLE773(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = msg.sender == _roles[uint256(role)].account; } function _ISPAUSED235(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING paused = _roles[uint256(role)].paused; } function _ISSMARTWALLET673( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _wallet_creation_code_header349, initialUserSigningKey, _wallet_creation_code_footer225 ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _create2_header144, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } function _REDEEMDDAIIFNECESSARY474(uint256 daiAmountFromReserves) internal { //inject NONSTANDARD NAMING uint256 daiBalance = _dai607.BALANCEOF7(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai635.REDEEMUNDERLYING444(additionalDaiRequired); } } function _TRANSFERTOKEN426(ERC20Interface token, address to, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.TRANSFER250.selector, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer out failed.' ); } function _TRANSFERETHER189(address recipient, uint256 etherAmount) internal { //inject NONSTANDARD NAMING // Send quoted Ether amount to recipient and revert with reason on failure. (bool ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function _TRANSFERINTOKEN55(ERC20Interface token, address from, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.TRANSFERFROM572.selector, from, address(this), amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer in failed.' ); } function _ENSURESMARTWALLET467( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal pure { require( _ISSMARTWALLET673(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); } function _CREATEPATHANDAMOUNTS240( //inject NONSTANDARD NAMING address start, address end, bool routeThroughEther ) internal pure returns (address[] memory, uint256[] memory) { uint256 pathLength = routeThroughEther ? 3 : 2; address[] memory path = new address[](pathLength); path[0] = start; if (routeThroughEther) { path[1] = _weth890; } path[pathLength - 1] = end; return (path, new uint256[](pathLength)); } modifier ONLYOWNEROR375(Role role) { //inject NONSTANDARD NAMING if (!ISOWNER119()) { require(_ISROLE773(role), "Caller does not have a required role."); require(!_ISPAUSED235(role), "Role in question is currently paused."); } _; } }
Some really janky tokens only allow setting approval up to current balance.
if (!success) { (success, data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), amount ) ); } require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." );
7,223,505
[ 1, 17358, 8654, 525, 2304, 93, 2430, 1338, 1699, 3637, 23556, 731, 358, 783, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 309, 16051, 4768, 13, 288, 203, 3639, 261, 4768, 16, 501, 13, 273, 1758, 12, 2316, 2934, 1991, 12, 203, 1850, 24126, 18, 3015, 1190, 4320, 12, 203, 5411, 1147, 18, 2203, 3373, 3412, 3672, 26, 18, 9663, 16, 1758, 24899, 318, 291, 91, 438, 67, 10717, 7140, 27, 3631, 3844, 203, 1850, 262, 203, 3639, 11272, 203, 1377, 289, 203, 203, 1377, 2583, 12, 203, 3639, 2216, 597, 261, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 892, 16, 261, 6430, 3719, 3631, 203, 3639, 315, 1345, 23556, 364, 1351, 291, 91, 438, 4633, 2535, 1199, 203, 1377, 11272, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000;
451,546
[ 1, 1289, 619, 66, 3600, 225, 261, 3707, 5, 342, 4711, 24949, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14087, 273, 261, 27005, 380, 389, 92, 13, 1671, 389, 14548, 31, 400, 1011, 14087, 380, 374, 92, 2787, 9449, 10321, 73, 27246, 2733, 71, 4630, 20, 72, 29, 9803, 11706, 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 ]
./full_match/4/0xd0356Dc3Bda0CDbCa00b5e4bB184a2fd98Df6E88/sources/contracts/Payable.sol
either receive() or fallback() is mandatory for the contract to receive ETH by sending ETH to the contract's address declaring the receive() function that is executed when sending ETH to the contract address it was introduced in Solidity 0.6 and a contract can have only one receive function, declared with this syntax (without the function keyword and without arguments).
contract Deposit{ receive() external payable{ } function getBalance() public view returns (uint) { return address(this).balance; } }
12,388,759
[ 1, 73, 2927, 6798, 1435, 578, 5922, 1435, 353, 11791, 364, 326, 6835, 358, 6798, 512, 2455, 635, 5431, 512, 2455, 358, 326, 6835, 1807, 1758, 20845, 326, 6798, 1435, 445, 716, 353, 7120, 1347, 5431, 512, 2455, 358, 326, 6835, 1758, 518, 1703, 26339, 316, 348, 7953, 560, 374, 18, 26, 471, 279, 6835, 848, 1240, 1338, 1245, 6798, 445, 16, 7886, 598, 333, 6279, 261, 13299, 326, 445, 4932, 471, 2887, 1775, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4019, 538, 305, 95, 203, 377, 203, 377, 203, 565, 6798, 1435, 3903, 8843, 429, 95, 203, 565, 289, 203, 27699, 7010, 377, 203, 27699, 377, 203, 540, 203, 7010, 565, 445, 2882, 6112, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 1758, 12, 2211, 2934, 12296, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xB08cb1C019718835600EE4446e6966eb8Fb3bA90/sources/project_/contracts/Marketplace1155.sol
uint256 private _listingFee = 1 ether;mapping from nft contract address to sellId to sellingInfo
contract Marketplace1155 is Ownable, IMarketplace1155 { uint256 private _listingFee = 0 ether; address private _marketOwner; mapping(bytes32 => ListedNFT) listedNftsList; pragma solidity ^0.8.6; constructor() { _marketOwner = msg.sender; } function _verifyCollection( address walletAddress, address nftContractAddress, address currencyContractAddress, uint256 tokenId, bytes memory signature ) internal pure returns (address) { return ECDSA.recover( keccak256( abi.encode( walletAddress, nftContractAddress, currencyContractAddress, tokenId ) ), signature ); } function getListedNFT( bytes32 listId ) external view returns (address, address, uint256, uint256, uint256, bool) { ListedNFT memory nft = listedNftsList[listId]; return ( nft.nftContractAddress, nft.owner, nft.tokenId, nft.amount, nft.price, nft.status ); } function getListingFee() external view returns (uint256) { return _listingFee; } function setListingFee(uint256 newFee) external onlyOwner { _listingFee = newFee; } function withdrawBalance() external payable onlyOwner { payable(msg.sender).transfer(address(this).balance); } function listNFT( bytes32 listId, address nftContractAddress, uint256 tokenId, uint256 amount, address currencyContractAddress, uint256 price, bytes memory signature ) external payable { require( msg.value >= _listingFee, "Marketplace: You have to pay us some fee for listing nft" ); require( _verifyCollection( msg.sender, nftContractAddress, currencyContractAddress, tokenId, signature ) == _marketOwner, "Marketplace: You are listing nfts belongs to an unregistered collection" ); require( IERC1155(nftContractAddress).balanceOf(msg.sender, tokenId) >= amount, "Marketplace: You cant list that much nfts for sale" ); require(price > 0, "Marketplace: You cannot sell these nfts for free"); listedNftsList[listId] = ListedNFT( listId, msg.sender, nftContractAddress, tokenId, amount, currencyContractAddress, price, true ); emit ListingNFT( listId, msg.sender, nftContractAddress, tokenId, amount, currencyContractAddress, price ); } function unlistNFT(bytes32 listId) external { ListedNFT memory listedNft = listedNftsList[listId]; require( listedNft.status == true, "Marketplace: You cannot unlist an unlisted batch of nfts" ); require( msg.sender == listedNft.owner, "Marketplace: You cannot unlist this batch of nfts" ); delete listedNft; emit UnlistNFT( listId, msg.sender, listedNft.nftContractAddress, listedNft.tokenId, listedNft.amount ); } function buyNFT(bytes32 listId) external payable { ListedNFT memory listedNft = listedNftsList[listId]; require(listedNft.status == true, "Marketplace: Invalid listId"); require( listedNft.owner != msg.sender, "Marketplace: You cannot buy your own nft" ); if (listedNft.currencyContractAddress == address(0)) { require( msg.value >= listedNft.price, "Marketplace: You dont have enough money to buy these batch of nfts" ); payable(listedNft.owner).transfer(listedNft.price * 1e18); uint256 balance = IERC20(listedNft.currencyContractAddress) .balanceOf(msg.sender); require( balance >= listedNft.price, "Marketplace: You dont have enough money to buy this nft" ); IERC20(listedNft.currencyContractAddress).transferFrom( msg.sender, listedNft.owner, listedNft.price ); } IERC1155(listedNft.nftContractAddress).safeTransferFrom( listedNft.owner, msg.sender, listedNft.tokenId, listedNft.amount, "" ); delete listedNftsList[listId]; emit BuyingNFT( msg.sender, listedNft.owner, listId, listedNft.nftContractAddress, listedNft.tokenId, listedNft.amount, listedNft.currencyContractAddress, listedNft.price ); } function buyNFT(bytes32 listId) external payable { ListedNFT memory listedNft = listedNftsList[listId]; require(listedNft.status == true, "Marketplace: Invalid listId"); require( listedNft.owner != msg.sender, "Marketplace: You cannot buy your own nft" ); if (listedNft.currencyContractAddress == address(0)) { require( msg.value >= listedNft.price, "Marketplace: You dont have enough money to buy these batch of nfts" ); payable(listedNft.owner).transfer(listedNft.price * 1e18); uint256 balance = IERC20(listedNft.currencyContractAddress) .balanceOf(msg.sender); require( balance >= listedNft.price, "Marketplace: You dont have enough money to buy this nft" ); IERC20(listedNft.currencyContractAddress).transferFrom( msg.sender, listedNft.owner, listedNft.price ); } IERC1155(listedNft.nftContractAddress).safeTransferFrom( listedNft.owner, msg.sender, listedNft.tokenId, listedNft.amount, "" ); delete listedNftsList[listId]; emit BuyingNFT( msg.sender, listedNft.owner, listId, listedNft.nftContractAddress, listedNft.tokenId, listedNft.amount, listedNft.currencyContractAddress, listedNft.price ); } } else { }
5,682,481
[ 1, 11890, 5034, 3238, 389, 21228, 14667, 273, 404, 225, 2437, 31, 6770, 628, 290, 1222, 6835, 1758, 358, 357, 80, 548, 358, 357, 2456, 966, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6622, 24577, 2499, 2539, 353, 14223, 6914, 16, 467, 3882, 24577, 2499, 2539, 288, 203, 565, 2254, 5034, 3238, 389, 21228, 14667, 273, 374, 225, 2437, 31, 203, 565, 1758, 3238, 389, 27151, 5541, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 987, 329, 50, 4464, 13, 12889, 50, 1222, 21576, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 26, 31, 203, 565, 3885, 1435, 288, 203, 3639, 389, 27151, 5541, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 8705, 2532, 12, 203, 3639, 1758, 9230, 1887, 16, 203, 3639, 1758, 290, 1222, 8924, 1887, 16, 203, 3639, 1758, 5462, 8924, 1887, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 3372, 203, 565, 262, 2713, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 327, 203, 5411, 7773, 19748, 18, 266, 3165, 12, 203, 7734, 417, 24410, 581, 5034, 12, 203, 10792, 24126, 18, 3015, 12, 203, 13491, 9230, 1887, 16, 203, 13491, 290, 1222, 8924, 1887, 16, 203, 13491, 5462, 8924, 1887, 16, 203, 13491, 1147, 548, 203, 10792, 262, 203, 7734, 262, 16, 203, 7734, 3372, 203, 5411, 11272, 203, 565, 289, 203, 203, 565, 445, 10033, 329, 50, 4464, 12, 203, 3639, 1731, 1578, 30790, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 16, 1758, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 1426, 13, 203, 565, 288, 203, 3639, 987, 329, 50, 4464, 3778, 290, 1222, 273, 12889, 2 ]
pragma solidity ^0.4.24; 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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Rays is ERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) private allowed; uint256 internal totalSupply_; event Burn(address indexed burner, uint256 value); string public name = "Rays Network"; string public symbol = "RAYS"; uint8 public decimals = 18; uint256 public constant INITIAL_SUPPLY = 500000000 * 10**18; constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * @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 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) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) public onlyOwner { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) public onlyOwner { require(_account != 0); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } } contract Crowdsale is Rays { // ICO rounds enum IcoStages {preSale, preIco, ico} IcoStages Stage; bool private crowdsaleFinished; uint private startPreSaleDate; uint private endPreSaleDate; uint public preSaleGoal; uint private preSaleRaised; uint private startPreIcoDate; uint private endPreIcoDate; uint public preIcoGoal; uint private preIcoRaised; uint private startIcoDate; uint private endIcoDate; uint public icoGoal; uint private icoRaised; uint private softCup; // 2 000 000 $ (300$ = 1 ether) uint private totalCup; uint private price; uint private total; uint private reserved; uint private hardCup;// 20 000 000 $ (300$ = 1 ether) struct Benefeciary{ // collect all participants of ICO address wallet; uint amount; } Benefeciary[] private benefeciary; uint private ethersRefund; constructor() public { startPreSaleDate = 1534723200; // insert here your pre sale start date endPreSaleDate = 1536969600; // insert here your pre sale end date preSaleGoal = 60000000; // pre-sale goal preSaleRaised = 0; // raised on pre-sale stage startPreIcoDate = 1534723200; // insert here your pre ico start date endPreIcoDate = 1538265600; // insert here your pre ico end date preIcoGoal = 60000000; // pre ico goal preIcoRaised = 0; // raised on pre ico startIcoDate = 1534723200; // insert here your ico start date endIcoDate = 1546214400; // insert here your ico end date icoGoal = 80000000; // ico goal icoRaised = 0; // raised on ico stage softCup = 6670 * 10**18; hardCup = 66670 * 10**18; totalCup = 0; price = 1160; total = preSaleGoal + preIcoGoal + icoGoal; reserved = (70000000 + 200000000 + 5000000 + 25000000) * 10**18; crowdsaleFinished = false; } function getCrowdsaleInfo() private returns(uint stage, uint tokenAvailable, uint bonus){ // Token calculating if(now <= endPreSaleDate && preSaleRaised < preSaleGoal){ Stage = IcoStages.preSale; tokenAvailable = preSaleGoal - preSaleRaised; total -= preSaleRaised; bonus = 0; // insert your bonus value on pre sale phase } else if(startPreIcoDate <= now && now <= endPreIcoDate && preIcoRaised < preIcoGoal){ Stage = IcoStages.preIco; tokenAvailable = preIcoGoal - preIcoRaised; total -= preIcoRaised; bonus = 50; // + 50% seems like bonus } else if(startIcoDate <= now && now <= endIcoDate && icoRaised < total){ tokenAvailable = total - icoRaised; Stage = IcoStages.ico; bonus = 0; } else { // if ICO has not been started revert(); } return (uint(Stage), tokenAvailable, bonus); } //per 0.1 ether will recieved 116 tokens function evaluateTokens(uint _value, address _sender) private returns(uint tokens){ ethersRefund = 0; uint bonus; uint tokenAvailable; uint stage; (stage,tokenAvailable,bonus) = getCrowdsaleInfo(); tokens = _value * price / 10**18; if(bonus != 0){ tokens = tokens + (tokens * bonus / 100); // calculate bonus tokens } if(tokenAvailable < tokens){ // if not enough tokens in reserve tokens = tokenAvailable; ethersRefund = _value - (tokens / price * 10**18); // calculate how many ethers will respond to user _sender.transfer(ethersRefund);// payback } owner.transfer(_value - ethersRefund); // Add token value to raised variable if(stage == 0){ preSaleRaised += tokens; } else if(stage == 1){ preIcoRaised += tokens; } else if(stage == 2){ icoRaised += tokens; } addInvestor(_sender, _value); return tokens; } function addInvestor(address _sender, uint _value) private { Benefeciary memory ben; for(uint i = 0; i < benefeciary.length; i++){ if(benefeciary[i].wallet == _sender){ benefeciary[i].amount = benefeciary[i].amount + _value - ethersRefund; } } ben.wallet = msg.sender; ben.amount = msg.value - ethersRefund; benefeciary.push(ben); } function() public payable { require(startPreSaleDate <= now && now <= endIcoDate); require(msg.value >= 0.1 ether); require(!crowdsaleFinished); totalCup += msg.value; uint token = evaluateTokens(msg.value, msg.sender); // send tokens to buyer balances[msg.sender] = balances[msg.sender].add(token * 10**18); balances[owner] = balances[owner].sub(token * 10**18); emit Transfer(owner, msg.sender, token * 10**18); } function showParticipantWei(address _wallet) public view onlyOwner returns(uint){ for(uint i = 0; i < benefeciary.length; i++){ if(benefeciary[i].wallet == _wallet){ return benefeciary[i].amount;// show in wei } } return 0; } function burnUnsoldTokens() public onlyOwner icoHasFinished{ _burn(owner, balanceOf(owner).sub(reserved)); } function crowdSaleStage() public view returns(string){ string memory result; if(uint(Stage) == 0){ result = "Pre Sale"; } else if(uint(Stage) == 1){ result = "Pre-ICO"; } else if(uint(Stage) == 2){ result = "ICO"; } return result; } function preSaleRaise() public view returns(uint){ return preSaleRaised; } function preIcoRaise() public view returns(uint){ return preIcoRaised; } function icoRaise() public view returns(uint){ return icoRaised; } modifier icoHasFinished() { require(now >= endIcoDate || icoRaised == total || crowdsaleFinished); _; } function endIcoByCup() public onlyOwner{ require(!crowdsaleFinished); require(totalCup >= softCup && totalCup <= hardCup); crowdsaleFinished = true; } // Output all funds in wei function showAllFunds() public onlyOwner view returns(uint){ return totalCup; } }
send tokens to buyer
function() public payable { require(startPreSaleDate <= now && now <= endIcoDate); require(msg.value >= 0.1 ether); require(!crowdsaleFinished); totalCup += msg.value; uint token = evaluateTokens(msg.value, msg.sender); balances[msg.sender] = balances[msg.sender].add(token * 10**18); balances[owner] = balances[owner].sub(token * 10**18); emit Transfer(owner, msg.sender, token * 10**18); }
12,656,330
[ 1, 4661, 2430, 358, 27037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 1937, 1386, 30746, 1626, 1648, 2037, 597, 2037, 1648, 679, 45, 2894, 1626, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 21, 225, 2437, 1769, 203, 3639, 2583, 12, 5, 71, 492, 2377, 5349, 10577, 1769, 203, 3639, 2078, 39, 416, 1011, 1234, 18, 1132, 31, 203, 3639, 2254, 1147, 273, 5956, 5157, 12, 3576, 18, 1132, 16, 1234, 18, 15330, 1769, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1289, 12, 2316, 380, 1728, 636, 2643, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 324, 26488, 63, 8443, 8009, 1717, 12, 2316, 380, 1728, 636, 2643, 1769, 203, 3639, 3626, 12279, 12, 8443, 16, 1234, 18, 15330, 16, 1147, 380, 1728, 636, 2643, 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 ]
pragma solidity >=0.5.4 <0.6.0; import './SafeMath.sol'; import './TAOController.sol'; import './ITAOPool.sol'; import './ITAOFactory.sol'; import './TAOCurrency.sol'; import './Logos.sol'; import './TAO.sol'; /** * @title TAOPool * * This contract acts as the bookkeeper of TAO Currencies that are staked on TAO */ contract TAOPool is TAOController, ITAOPool { using SafeMath for uint256; address public taoFactoryAddress; address public pathosAddress; address public ethosAddress; address public logosAddress; ITAOFactory internal _taoFactory; TAOCurrency internal _pathos; TAOCurrency internal _ethos; Logos internal _logos; struct Pool { address taoId; /** * If true, has ethos cap. Otherwise, no ethos cap. */ bool ethosCapStatus; uint256 ethosCapAmount; // Creates a cap for the amount of Ethos that can be staked into this pool /** * If true, Pool is live and can be staked into. */ bool status; } struct EthosLot { bytes32 ethosLotId; // The ID of this Lot address nameId; // The ID of the Name that staked Ethos uint256 lotQuantity; // Amount of Ethos being staked to the Pool from this Lot address taoId; // Identifier for the Pool this Lot is adding to uint256 poolPreStakeSnapshot; // Amount of Ethos contributed to the Pool prior to this Lot Number uint256 poolStakeLotSnapshot; // poolPreStakeSnapshot + lotQuantity uint256 lotValueInLogos; uint256 logosWithdrawn; // Amount of Logos withdrawn from this Lot uint256 timestamp; } uint256 public contractTotalEthosLot; // Total Ethos lot from all pools uint256 public contractTotalPathosStake; // Total Pathos stake from all pools (how many Pathos stakes are there in contract) uint256 public contractTotalEthos; // Quantity of Ethos that has been staked to all Pools uint256 public contractTotalPathos; // Quantity of Pathos that has been staked to all Pools uint256 public contractTotalLogosWithdrawn; // Quantity of Logos that has been withdrawn from all Pools // Mapping from TAO ID to Pool mapping (address => Pool) public pools; // Mapping from Ethos Lot ID to Ethos Lot mapping (bytes32 => EthosLot) public ethosLots; // Mapping from Pool's TAO ID to total Ethos Lots in the Pool mapping (address => uint256) public poolTotalEthosLot; // Mapping from Pool's TAO ID to quantity of Logos that has been withdrawn from the Pool mapping (address => uint256) public poolTotalLogosWithdrawn; // Mapping from a Name ID to its Ethos Lots mapping (address => bytes32[]) internal ownerEthosLots; // Mapping from a Name ID to quantity of Ethos staked from all Ethos lots mapping (address => uint256) public totalEthosStaked; // Mapping from a Name ID to quantity of Pathos staked from all Ethos lots mapping (address => uint256) public totalPathosStaked; // Mapping from a Name ID to total Logos withdrawn from all Ethos lots mapping (address => uint256) public totalLogosWithdrawn; // Mapping from a Name ID to quantity of Ethos staked from all Ethos lots on a Pool mapping (address => mapping (address => uint256)) public namePoolEthosStaked; // Mapping from a Name ID to quantity of Pathos staked on a Pool mapping (address => mapping (address => uint256)) public namePoolPathosStaked; // Mapping from a Name ID to quantity of Logos withdrawn from a Pool mapping (address => mapping (address => uint256)) public namePoolLogosWithdrawn; // Event to be broadcasted to public when Pool is created event CreatePool(address indexed taoId, bool ethosCapStatus, uint256 ethosCapAmount, bool status); // Event to be broadcasted to public when Pool's status is updated // If status == true, start Pool // Otherwise, stop Pool event UpdatePoolStatus(address indexed taoId, bool status, uint256 nonce); // Event to be broadcasted to public when Pool's Ethos cap is updated event UpdatePoolEthosCap(address indexed taoId, bool ethosCapStatus, uint256 ethosCapAmount, uint256 nonce); /** * Event to be broadcasted to public when nameId stakes Ethos */ event StakeEthos(address indexed taoId, bytes32 indexed ethosLotId, address indexed nameId, uint256 lotQuantity, uint256 poolPreStakeSnapshot, uint256 poolStakeLotSnapshot, uint256 lotValueInLogos, uint256 timestamp); // Event to be broadcasted to public when nameId stakes Pathos event StakePathos(address indexed taoId, bytes32 indexed stakeId, address indexed nameId, uint256 stakeQuantity, uint256 currentPoolTotalStakedPathos, uint256 timestamp); // Event to be broadcasted to public when nameId withdraws Logos from Ethos Lot event WithdrawLogos(address indexed nameId, bytes32 indexed ethosLotId, address indexed taoId, uint256 withdrawnAmount, uint256 currentLotValueInLogos, uint256 currentLotLogosWithdrawn, uint256 timestamp); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _taoFactoryAddress, address _nameTAOPositionAddress, address _pathosAddress, address _ethosAddress, address _logosAddress) TAOController(_nameFactoryAddress) public { setTAOFactoryAddress(_taoFactoryAddress); setNameTAOPositionAddress(_nameTAOPositionAddress); setPathosAddress(_pathosAddress); setEthosAddress(_ethosAddress); setLogosAddress(_logosAddress); } /** * @dev Check if calling address is TAO Factory address */ modifier onlyTAOFactory { require (msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the TAOFactory Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = ITAOFactory(_taoFactoryAddress); } /** * @dev The AO set the Pathos Address * @param _pathosAddress The address of Pathos */ function setPathosAddress(address _pathosAddress) public onlyTheAO { require (_pathosAddress != address(0)); pathosAddress = _pathosAddress; _pathos = TAOCurrency(_pathosAddress); } /** * @dev The AO set the Ethos Address * @param _ethosAddress The address of Ethos */ function setEthosAddress(address _ethosAddress) public onlyTheAO { require (_ethosAddress != address(0)); ethosAddress = _ethosAddress; _ethos = TAOCurrency(_ethosAddress); } /** * @dev The AO set the Logos Address * @param _logosAddress The address of Logos */ function setLogosAddress(address _logosAddress) public onlyTheAO { require (_logosAddress != address(0)); logosAddress = _logosAddress; _logos = Logos(_logosAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not Pool exist for a TAO ID * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return pools[_id].taoId != address(0); } /** * @dev Create a pool for a TAO */ function createPool( address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount ) external isTAO(_taoId) onlyTAOFactory returns (bool) { // Make sure ethos cap amount is provided if ethos cap is enabled if (_ethosCapStatus) { require (_ethosCapAmount > 0); } // Make sure the pool is not yet created require (pools[_taoId].taoId == address(0)); Pool storage _pool = pools[_taoId]; _pool.taoId = _taoId; _pool.status = true; _pool.ethosCapStatus = _ethosCapStatus; if (_ethosCapStatus) { _pool.ethosCapAmount = _ethosCapAmount; } emit CreatePool(_pool.taoId, _pool.ethosCapStatus, _pool.ethosCapAmount, _pool.status); return true; } /** * @dev Start/Stop a Pool * @param _taoId The TAO ID of the Pool * @param _status The status to set. true = start. false = stop */ function updatePoolStatus(address _taoId, bool _status) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised { require (pools[_taoId].taoId != address(0)); pools[_taoId].status = _status; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit UpdatePoolStatus(_taoId, _status, _nonce); } /** * @dev Update Ethos cap of a Pool * @param _taoId The TAO ID of the Pool * @param _ethosCapStatus The ethos cap status to set * @param _ethosCapAmount The ethos cap amount to set */ function updatePoolEthosCap(address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised { require (pools[_taoId].taoId != address(0)); // If there is an ethos cap if (_ethosCapStatus) { require (_ethosCapAmount > 0 && _ethosCapAmount > _pathos.balanceOf(_taoId)); } pools[_taoId].ethosCapStatus = _ethosCapStatus; if (_ethosCapStatus) { pools[_taoId].ethosCapAmount = _ethosCapAmount; } uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit UpdatePoolEthosCap(_taoId, _ethosCapStatus, _ethosCapAmount, _nonce); } /** * @dev A Name stakes Ethos in Pool `_taoId` * @param _taoId The TAO ID of the Pool * @param _quantity The amount of Ethos to be staked */ function stakeEthos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised { Pool memory _pool = pools[_taoId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_pool.status == true && _quantity > 0 && _ethos.balanceOf(_nameId) >= _quantity); // If there is an ethos cap if (_pool.ethosCapStatus) { require (_ethos.balanceOf(_taoId).add(_quantity) <= _pool.ethosCapAmount); } // Create Ethos Lot for this transaction contractTotalEthosLot++; poolTotalEthosLot[_taoId]++; // Generate Ethos Lot ID bytes32 _ethosLotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalEthosLot)); EthosLot storage _ethosLot = ethosLots[_ethosLotId]; _ethosLot.ethosLotId = _ethosLotId; _ethosLot.nameId = _nameId; _ethosLot.lotQuantity = _quantity; _ethosLot.taoId = _taoId; _ethosLot.poolPreStakeSnapshot = _ethos.balanceOf(_taoId); _ethosLot.poolStakeLotSnapshot = _ethos.balanceOf(_taoId).add(_quantity); _ethosLot.lotValueInLogos = _quantity; _ethosLot.timestamp = now; ownerEthosLots[_nameId].push(_ethosLotId); // Update contract variables totalEthosStaked[_nameId] = totalEthosStaked[_nameId].add(_quantity); namePoolEthosStaked[_nameId][_taoId] = namePoolEthosStaked[_nameId][_taoId].add(_quantity); contractTotalEthos = contractTotalEthos.add(_quantity); require (_ethos.transferFrom(_nameId, _taoId, _quantity)); emit StakeEthos(_ethosLot.taoId, _ethosLot.ethosLotId, _ethosLot.nameId, _ethosLot.lotQuantity, _ethosLot.poolPreStakeSnapshot, _ethosLot.poolStakeLotSnapshot, _ethosLot.lotValueInLogos, _ethosLot.timestamp); } /** * @dev Retrieve number of Ethos Lots a `_nameId` has * @param _nameId The Name ID of the Ethos Lot's owner * @return Total Ethos Lots the owner has */ function ownerTotalEthosLot(address _nameId) public view returns (uint256) { return ownerEthosLots[_nameId].length; } /** * @dev Get list of owner's Ethos Lot IDs from `_from` to `_to` index * @param _nameId The Name Id of the Ethos Lot's owner * @param _from The starting index, (i.e 0) * @param _to The ending index, (i.e total - 1) * @return list of owner's Ethos Lot IDs */ function ownerEthosLotIds(address _nameId, uint256 _from, uint256 _to) public view returns (bytes32[] memory) { require (_from >= 0 && _to >= _from && ownerEthosLots[_nameId].length > _to); bytes32[] memory _ethosLotIds = new bytes32[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _ethosLotIds[i.sub(_from)] = ownerEthosLots[_nameId][i]; } return _ethosLotIds; } /** * @dev Return the amount of Pathos that can be staked on Pool * @param _taoId The TAO ID of the Pool * @return The amount of Pathos that can be staked */ function availablePathosToStake(address _taoId) public isTAO(_taoId) view returns (uint256) { if (pools[_taoId].status == true) { return _ethos.balanceOf(_taoId).sub(_pathos.balanceOf(_taoId)); } else { return 0; } } /** * @dev A Name stakes Pathos in Pool `_taoId` * @param _taoId The TAO ID of the Pool * @param _quantity The amount of Pathos to stake */ function stakePathos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised { Pool memory _pool = pools[_taoId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_pool.status == true && _quantity > 0 && _pathos.balanceOf(_nameId) >= _quantity && _quantity <= availablePathosToStake(_taoId)); // Update contract variables contractTotalPathosStake++; totalPathosStaked[_nameId] = totalPathosStaked[_nameId].add(_quantity); namePoolPathosStaked[_nameId][_taoId] = namePoolPathosStaked[_nameId][_taoId].add(_quantity); contractTotalPathos = contractTotalPathos.add(_quantity); // Generate Pathos Stake ID bytes32 _stakeId = keccak256(abi.encodePacked(this, msg.sender, contractTotalPathosStake)); require (_pathos.transferFrom(_nameId, _taoId, _quantity)); // Also add advocated TAO logos to Advocate of _taoId require (_logos.addAdvocatedTAOLogos(_taoId, _quantity)); emit StakePathos(_taoId, _stakeId, _nameId, _quantity, _pathos.balanceOf(_taoId), now); } /** * @dev Name that staked Ethos withdraw Logos from Ethos Lot `_ethosLotId` * @param _ethosLotId The ID of the Ethos Lot */ function withdrawLogos(bytes32 _ethosLotId) public senderIsName senderNameNotCompromised { EthosLot storage _ethosLot = ethosLots[_ethosLotId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_ethosLot.nameId == _nameId && _ethosLot.lotValueInLogos > 0); uint256 logosAvailableToWithdraw = lotLogosAvailableToWithdraw(_ethosLotId); require (logosAvailableToWithdraw > 0 && logosAvailableToWithdraw <= _ethosLot.lotValueInLogos); // Update lot variables _ethosLot.logosWithdrawn = _ethosLot.logosWithdrawn.add(logosAvailableToWithdraw); _ethosLot.lotValueInLogos = _ethosLot.lotValueInLogos.sub(logosAvailableToWithdraw); // Update contract variables contractTotalLogosWithdrawn = contractTotalLogosWithdrawn.add(logosAvailableToWithdraw); poolTotalLogosWithdrawn[_ethosLot.taoId] = poolTotalLogosWithdrawn[_ethosLot.taoId].add(logosAvailableToWithdraw); totalLogosWithdrawn[_ethosLot.nameId] = totalLogosWithdrawn[_ethosLot.nameId].add(logosAvailableToWithdraw); namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId] = namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId].add(logosAvailableToWithdraw); // Mint logos to seller require (_logos.mint(_nameId, logosAvailableToWithdraw)); emit WithdrawLogos(_ethosLot.nameId, _ethosLot.ethosLotId, _ethosLot.taoId, logosAvailableToWithdraw, _ethosLot.lotValueInLogos, _ethosLot.logosWithdrawn, now); } /** * @dev Name gets Ethos Lot `_ethosLotId` available Logos to withdraw * @param _ethosLotId The ID of the Ethos Lot * @return The amount of Logos available to withdraw */ function lotLogosAvailableToWithdraw(bytes32 _ethosLotId) public view returns (uint256) { EthosLot memory _ethosLot = ethosLots[_ethosLotId]; require (_ethosLot.nameId != address(0)); uint256 logosAvailableToWithdraw = 0; if (_pathos.balanceOf(_ethosLot.taoId) > _ethosLot.poolPreStakeSnapshot && _ethosLot.lotValueInLogos > 0) { logosAvailableToWithdraw = (_pathos.balanceOf(_ethosLot.taoId) >= _ethosLot.poolStakeLotSnapshot) ? _ethosLot.lotQuantity : _pathos.balanceOf(_ethosLot.taoId).sub(_ethosLot.poolPreStakeSnapshot); if (logosAvailableToWithdraw > 0) { logosAvailableToWithdraw = logosAvailableToWithdraw.sub(_ethosLot.logosWithdrawn); } } return logosAvailableToWithdraw; } }
* Event to be broadcasted to public when nameId stakes Ethos/
event StakeEthos(address indexed taoId, bytes32 indexed ethosLotId, address indexed nameId, uint256 lotQuantity, uint256 poolPreStakeSnapshot, uint256 poolStakeLotSnapshot, uint256 lotValueInLogos, uint256 timestamp);
12,935,861
[ 1, 1133, 358, 506, 8959, 329, 358, 1071, 1347, 508, 548, 384, 3223, 512, 451, 538, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 2575, 934, 911, 41, 451, 538, 12, 2867, 8808, 17433, 548, 16, 1731, 1578, 8808, 13750, 538, 48, 352, 548, 16, 1758, 8808, 508, 548, 16, 2254, 5034, 17417, 12035, 16, 2254, 5034, 2845, 1386, 510, 911, 4568, 16, 2254, 5034, 2845, 510, 911, 48, 352, 4568, 16, 2254, 5034, 17417, 620, 382, 1343, 538, 16, 2254, 5034, 2858, 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 ]
./partial_match/3/0x48CEDc686E9a368256Ee4344880556a5312Fdc24/sources/wearables_distribution.sol
@notice only contract's owner have the right to add merkleroot. @dev set _merkelRoot @param _merkelRoot provide the merkleroot to enable merkle verification
function setmerkleroot(bytes32 _merkelRoot) private onlyOwner { merkleRoot = _merkelRoot; }
5,126,990
[ 1, 3700, 6835, 1807, 3410, 1240, 326, 2145, 358, 527, 4045, 79, 749, 1632, 18, 225, 444, 389, 6592, 79, 292, 2375, 225, 389, 6592, 79, 292, 2375, 5615, 326, 4045, 79, 749, 1632, 358, 4237, 30235, 11805, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 6592, 79, 749, 1632, 12, 3890, 1578, 225, 389, 6592, 79, 292, 2375, 13, 3238, 1338, 5541, 288, 203, 3639, 30235, 2375, 273, 389, 6592, 79, 292, 2375, 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 ]
./partial_match/1/0x11D635bbba3f9B8f7C9b91cA9f315a2207cb5AD5/sources/dHealthToken.sol
* @dev Constructor that initializes token contract with token address in parameter/ set token set growth contract address
public { token = dHealthToken(_token); growthContract = _growthContract; }
9,236,461
[ 1, 6293, 716, 11643, 1147, 6835, 598, 1147, 1758, 316, 1569, 19, 444, 1147, 444, 13334, 451, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 482, 288, 203, 202, 202, 2316, 273, 302, 7802, 1345, 24899, 2316, 1769, 203, 203, 202, 202, 75, 492, 451, 8924, 273, 389, 75, 492, 451, 8924, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1313161554/0x51e20134b7c11D9e868E0EE227BAbc429CA1c2e8/sources/contracts/libraries/LibSwapper.sol
@notice A call to another dex or contract done and here is the result @param target The address of dex or contract that is called @param success A boolean indicating that the call was success or not @param returnData The response of function call
event CallResult(address target, bool success, bytes returnData);
13,230,287
[ 1, 37, 745, 358, 4042, 302, 338, 578, 6835, 2731, 471, 2674, 353, 326, 563, 225, 1018, 1021, 1758, 434, 302, 338, 578, 6835, 716, 353, 2566, 225, 2216, 432, 1250, 11193, 716, 326, 745, 1703, 2216, 578, 486, 225, 327, 751, 1021, 766, 434, 445, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 871, 3049, 1253, 12, 2867, 1018, 16, 1426, 2216, 16, 1731, 327, 751, 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 ]
// SPDX-License-Identifier: No License (None) pragma solidity ^0.8.0; import "./TransferHelper.sol"; interface IERC20 { function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); } interface IValidator { // returns rate (with 18 decimals) = Token B price / Token A price function getRate(address tokenA, address tokenB) external returns (uint256); // returns: user balance, native (foreign for us) encoded balance, foreign (native for us) encoded balance function checkBalances(address factory, address[] calldata user) external returns(uint256); // returns: user balance function checkBalance(address factory, address user) external returns(uint256); // returns: oracle fee function getOracleFee(uint256 req) external returns(uint256); //req: 1 - cancel, 2 - claim, returns: value } interface ISmart { function requestCompensation(address user, uint256 feeAmount) external returns(bool); } interface IAuction { function contributeFromSmartSwap(address payable user) external payable returns (bool); function contributeFromSmartSwap(address token, uint256 amount, address user) external returns (bool); } abstract contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ /* we use proxy, so owner will be set in initialize() function constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } */ /** * @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() == msg.sender, "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 transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract SmartSwap is Ownable { struct Cancel { uint64 pairID; // pair ID address sender; // user who has to receive canceled amount uint256 amount; // amount of token user want to cancel from order //uint128 foreignBalance; // amount of token already swapped (on other chain) } struct Claim { uint64 pairID; // pair ID address sender; // address who send tokens to swap address receiver; // address who has to receive swapped amount uint64 claimID; // uniq claim ID bool isInvestment; // is claim to contributeFromSmartSwap uint128 amount; // amount of foreign tokens user want to swap uint128 currentRate; uint256 foreignBalance; //[0] foreignBalance, [1] foreignSpent, [2] nativeSpent, [3] nativeRate } struct Pair { address tokenA; address tokenB; } address constant NATIVE_COINS = 0x0000000000000000000000000000000000000009; // 1 - BNB, 2 - ETH, 3 - BTC uint256 constant NOMINATOR = 10**18; uint256 constant MAX_AMOUNT = 2**128; address public foreignFactory; address payable public validator; uint256 public rateDiffLimit; // allowed difference (in percent) between LP provided rate and Oracle rate. mapping(address => bool) public isSystem; // system address mey change fee amount address public auction; // auction address address public contractSmart; // the contract address to request Smart token in exchange of fee mapping (address => uint256) licenseeFee; // the licensee may set personal fee (in percent wih 2 decimals). It have to compensate this fee with own tokens. mapping (address => address) licenseeCompensator; // licensee contract which will compensate fee with tokens mapping(address => bool) public isExchange; // is Exchange address mapping(address => bool) public isExcludedSender; // address excluded from receiving SMART token as fee compensation // fees uint256 public swapGasReimbursement; // percentage of swap Gas Reimbursement by SMART tokens uint256 public companyFeeReimbursement; // percentage of company Fee Reimbursement by SMART tokens uint256 public cancelGasReimbursement; // percentage of cancel Gas Reimbursement by SMART tokens uint256 public companyFee; // the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3% uint256 public processingFee; // the fee in base coin, to compensate Gas when back-end call claimTokenBehalf() address public feeReceiver; // address which receive the fee (by default is validator) uint256 private collectedFees; // amount of collected fee (starts from 1 to avoid additional gas usage) mapping(address => uint256) public decimals; // token address => token decimals uint256 public pairIDCounter; mapping(uint256 => Pair) public getPairByID; mapping(address => mapping(address => uint256)) public getPairID; // tokenA => tokenB => pair ID or 0 if not exist mapping(uint256 => uint256) public totalSupply; // pairID => totalSupply amount of tokenA on the pair // hashAddress = address(keccak256(tokenA, tokenB, sender, receiver)) mapping(address => uint256) private _balanceOf; // hashAddress => amount of tokenA mapping(address => Cancel) public cancelRequest; // hashAddress => amount of tokenA to cancel mapping(address => Claim) public claimRequest; // hashAddress => amount of tokenA to swap mapping(address => bool) public isLiquidityProvider; // list of Liquidity Providers uint256 claimIdCounter; // counter of claim requests // ============================ Events ============================ event PairAdded(address indexed tokenA, address indexed tokenB, uint256 indexed pairID); event PairRemoved(address indexed tokenA, address indexed tokenB, uint256 indexed pairID); event SwapRequest( address indexed tokenA, address indexed tokenB, address indexed sender, address receiver, uint256 amountA, bool isInvestment, uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled. uint128 limitPice // Do not match user if token A price less this limit ); event CancelRequest(address indexed hashAddress, uint256 amount); event CancelApprove(address indexed hashAddress, uint256 newBalance); event ClaimRequest(address indexed hashAddress, uint64 claimID, uint256 amount, bool isInvestment); event ClaimApprove(address indexed hashAddress, uint64 claimID, uint256 nativeAmount, uint256 foreignAmount, bool isInvestment); event ExchangeInvestETH(address indexed exchange, address indexed whom, uint256 value); event SetSystem(address indexed system, bool active); event SetLicensee(address indexed system, address indexed compensator); /** * @dev Throws if called by any account other than the system. */ modifier onlySystem() { require(isSystem[msg.sender] || owner() == msg.sender, "Caller is not the system"); _; } // run only once from proxy function initialize(address newOwner) external { require(newOwner != address(0) && _owner == address(0)); // run only once _owner = newOwner; emit OwnershipTransferred(address(0), msg.sender); rateDiffLimit = 5; // allowed difference (in percent) between LP provided rate and Oracle rate. swapGasReimbursement = 100; // percentage of swap Gas Reimbursement by SMART tokens companyFeeReimbursement = 100; // percentage of company Fee Reimbursement by SMART tokens cancelGasReimbursement = 100; // percentage of cancel Gas Reimbursement by SMART tokens companyFee = 0; // the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3% collectedFees = 1; // amount of collected fee (starts from 1 to avoid additional gas usage) } // get amount of collected fees that can be claimed function getColletedFees() external view returns (uint256) { // collectedFees starts from 1 to avoid additional gas usage to initiate storage (when collectedFees = 0) return collectedFees - 1; } // claim fees by feeReceiver function claimFee() external returns (uint256 feeAmount) { require(msg.sender == feeReceiver); feeAmount = collectedFees - 1; collectedFees = 1; TransferHelper.safeTransferETH(msg.sender, feeAmount); } function balanceOf(address hashAddress) external view returns(uint256) { return _balanceOf[hashAddress]; } // return balance for swap function getBalance( address tokenA, address tokenB, address sender, address receiver ) external view returns (uint256) { return _balanceOf[_getHashAddress(tokenA, tokenB, sender, receiver)]; } function getHashAddress( address tokenA, address tokenB, address sender, address receiver ) external pure returns (address) { return _getHashAddress(tokenA, tokenB, sender, receiver); } //user should approve tokens transfer before calling this function. //if no licensee set it to address(0) function swap( address tokenA, address tokenB, address receiver, uint256 amountA, address licensee, bool isInvestment, uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled. uint128 limitPice // Do not match user if token A price less this limit ) external payable returns (bool) { _transferFee(tokenA, amountA, msg.sender, licensee); _swap(tokenA, tokenB, msg.sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice); return true; } function cancel( address tokenA, address tokenB, address receiver, uint256 amountA //amount of tokenA to cancel ) external payable returns (bool) { _cancel(tokenA, tokenB, msg.sender, receiver, amountA); return true; } function claimTokenBehalf( address tokenA, // foreignToken address tokenB, // nativeToken address sender, address receiver, bool isInvestment, uint128 amountA, //amount of tokenA that has to be swapped uint128 currentRate, // rate with 18 decimals: tokenA price / tokenB price uint256 foreignBalance // total tokens amount sent by user to pair on other chain ) external onlySystem returns (bool) { _claimTokenBehalf(tokenA, tokenB, sender, receiver, isInvestment, amountA, currentRate, foreignBalance); return true; } // add liquidity to counterparty function addLiquidityAndClaimBehalf( address tokenA, // Native token address tokenB, // Foreign token address receiver, bool isInvestment, uint128 amountA, //amount of tokenA that has to be swapped uint128 currentRate, // rate with 18 decimals: tokenB price / tokenA price uint256 foreignBalance, // total tokens amount sent by user to pair on other chain address senderCounterparty, address receiverCounterparty ) external payable onlySystem returns (bool) { _transferFee(tokenA, amountA, msg.sender, address(0)); _swap(tokenA, tokenB, msg.sender, receiver, amountA, false,0,0); uint256 amountB = amountA * 10**(18+decimals[tokenB]-decimals[tokenA]) / currentRate; _claimTokenBehalf(tokenB, tokenA, senderCounterparty, receiverCounterparty, isInvestment, uint128(amountB), currentRate, foreignBalance); return true; } function balanceCallback(address hashAddress, uint256 foreignBalance) external returns(bool) { require (validator == msg.sender, "Not validator"); _cancelApprove(hashAddress, foreignBalance); return true; } function balancesCallback( address hashAddress, uint256 foreignBalance, // total user's tokens balance on foreign chain uint256 foreignSpent, // total tokens spent by SmartSwap pair uint256 nativeEncoded // (nativeRate, nativeSpent) = _decode(nativeEncoded) ) external returns(bool) { require (validator == msg.sender, "Not validator"); _claimBehalfApprove(hashAddress, foreignBalance, foreignSpent, nativeEncoded); return true; } // get system variables for debugging function getPairVars(uint256 pairID) external view returns (uint256 native, uint256 foreign, uint256 foreignRate) { address nativeHash = _getHashAddress(getPairByID[pairID].tokenA, getPairByID[pairID].tokenB, address(0), address(0)); address foreignHash = _getHashAddress(getPairByID[pairID].tokenB, getPairByID[pairID].tokenA, address(0), address(0)); // native - amount of native tokens that swapped from available foreign native = _balanceOf[nativeHash]; // foreign = total foreign tokens already swapped // foreignRate = rate (native price / foreign price) of available foreign tokens on other chain (foreignRate, foreign) = _decode(_balanceOf[foreignHash]); // Example: assume system vars = 0, rate of prices ETH/BNB = 2 (or BNB/ETH = 0.5) // on ETH chain: // 1. claim ETH for 60 BNB == 60 * 0.5 = 30 ETH, // set: foreign = 60 BNB, foreignRate = 0.5 BNB/ETH prices (already swapped BNB) // // on BSC chain: // 2. claim BNB for 20 ETH, assume new rate of prices ETH/BNB = 4 (or BNB/ETH = 0.25) // get from ETH chain foreign(ETH) = 60 BNB, foreignRate(ETH) = 0.5 BNB/ETH prices // available amount of already swapped BNB = 60 BNB (foreign from ETH) - 0 BNB (native) = 60 BNB with rate 0.5 BNB/ETH // claimed BNB amount = 20 ETH / 0.5 BNB/ETH = 40 BNB (we use rate of already swapped BNB) // set: native = 40 BNB (we use BNB that was already swapped on step 1) // // 3. New claim BNB for 30 ETH, assume new rate of prices ETH/BNB = 4 (or BNB/ETH = 0.25) // get from ETH chain foreign(ETH) = 60 BNB, foreignRate(ETH) = 0.5 BNB/ETH prices // available amount of already swapped BNB = 60 BNB (foreign from ETH) - 40 BNB (native) = 20 BNB with rate 0.5 BNB/ETH // 20 BNB * 0.5 = 10 ETH (we claimed 20 BNB for 10 ETH with already swapped rate) // set: native = 40 BNB + 20 BNB = 60 BNB (we use all BNB that was already swapped on step 1) // claimed rest BNB amount for (30-10) ETH = 20 ETH / 0.25 BNB/ETH = 80 BNB (we use new rate) // set: foreign = 20 ETH, foreignRate = 0.25 BNB/ETH prices (already swapped ETH) } // ================== For Jointer Auction ========================================================================= // ETH side // function for invest ETH from from exchange on user behalf function contributeWithEtherBehalf(address payable _whom) external payable returns (bool) { require(isExchange[msg.sender], "Not an Exchange address"); address tokenA = address(2); // ETH (native coin) address tokenB = address(1); // BNB (foreign coin) uint256 amount = msg.value - processingFee; emit ExchangeInvestETH(msg.sender, _whom, msg.value); _transferFee(tokenA, amount, _whom, address(0)); // no licensee _swap(tokenA, tokenB, _whom, auction, amount, true,0,0); return true; } // BSC side // tokenB - foreign token address or address(1) for ETH // amountB - amount of foreign tokens or ETH function claimInvestmentBehalf( address tokenB, // foreignToken address user, uint128 amountB, //amount of tokenB that has to be swapped uint128 currentRate, // rate with 18 decimals: tokenB price / Native coin price uint256 foreignBalance // total tokens amount sent by user to pair on other chain ) external onlySystem returns (bool) { address tokenA = address(1); // BNB (native coin) _claimTokenBehalf(tokenB, tokenA, user, auction, true, amountB, currentRate, foreignBalance); return true; } // ================= END For Jointer Auction =========================================================================== // ============================ Restricted functions ============================ // set processing fee - amount that have to be paid on other chain to claimTokenBehalf. // Set in amount of native coins (BNB or ETH) function setProcessingFee(uint256 _fee) external onlySystem returns(bool) { processingFee = _fee; return true; } // set licensee compensator contract address, if this address is address(0) - remove licensee. // compensator contract has to compensate the fee by other tokens. // licensee fee in percent with 2 decimals. I.e. 10 = 0.1% function setLicensee(address _licensee, address _compensator, uint256 _fee) external onlySystem returns(bool) { licenseeCompensator[_licensee] = _compensator; require(_fee < 10000, "too big fee"); // fee should be less then 100% licenseeFee[_licensee] = _fee; emit SetLicensee(_licensee, _compensator); return true; } // set licensee fee in percent with 2 decimals. I.e. 10 = 0.1% function setLicenseeFee(uint256 _fee) external returns(bool) { require(licenseeCompensator[msg.sender] != address(0), "licensee is not registered"); require(_fee < 10000, "too big fee"); // fee should be less then 100% licenseeFee[msg.sender] = _fee; return true; } // ============================ Owner's functions ============================ //the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3% function setCompanyFee(uint256 _fee) external onlyOwner returns(bool) { require(_fee < 10000, "too big fee"); // fee should be less then 100% companyFee = _fee; return true; } // Reimbursement Percentage without decimals: 100 = 100% function setReimbursementPercentage (uint256 id, uint256 _fee) external onlyOwner returns(bool) { if (id == 1) swapGasReimbursement = _fee; // percentage of swap Gas Reimbursement by SMART tokens else if (id == 2) cancelGasReimbursement = _fee; // percentage of cancel Gas Reimbursement by SMART tokens else if (id == 3) companyFeeReimbursement = _fee; // percentage of company Fee Reimbursement by SMART tokens return true; } function setSystem(address _system, bool _active) external onlyOwner returns(bool) { isSystem[_system] = _active; emit SetSystem(_system, _active); return true; } function setValidator(address payable _validator) external onlyOwner returns(bool) { validator = _validator; return true; } function setForeignFactory(address _addr) external onlyOwner returns(bool) { foreignFactory = _addr; return true; } function setFeeReceiver(address _addr) external onlyOwner returns(bool) { feeReceiver = _addr; return true; } function setMSSContract(address _addr) external onlyOwner returns(bool) { contractSmart = _addr; return true; } function setAuction(address _addr) external onlyOwner returns(bool) { auction = _addr; return true; } // for ETH side only function changeExchangeAddress(address _which,bool _bool) external onlyOwner returns(bool){ isExchange[_which] = _bool; return true; } function changeExcludedAddress(address _which,bool _bool) external onlyOwner returns(bool){ isExcludedSender[_which] = _bool; return true; } function createPair(address tokenA, uint256 decimalsA, address tokenB, uint256 decimalsB) public onlyOwner returns (uint256) { require(getPairID[tokenA][tokenB] == 0, "Pair exist"); uint256 pairID = ++pairIDCounter; getPairID[tokenA][tokenB] = pairID; getPairByID[pairID] = Pair(tokenA, tokenB); if (decimals[tokenA] == 0) decimals[tokenA] = decimalsA; if (decimals[tokenB] == 0) decimals[tokenB] = decimalsB; return pairID; } // ============================ Internal functions ============================ function _swap( address tokenA, // nativeToken address tokenB, // foreignToken address sender, address receiver, uint256 amountA, bool isInvestment, uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled. uint128 limitPice // Do not match user if token A price less this limit ) internal { uint256 pairID = getPairID[tokenA][tokenB]; require(pairID != 0, "Pair not exist"); if (tokenA > NATIVE_COINS) { TransferHelper.safeTransferFrom(tokenA, sender, address(this), amountA); } // (amount >= msg.value) is checking when pay fee in the function transferFee() address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver); _balanceOf[hashAddress] += amountA; totalSupply[pairID] += amountA; emit SwapRequest(tokenA, tokenB, sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice); } function _cancel( address tokenA, // nativeToken address tokenB, // foreignToken address sender, address receiver, uint256 amountA //amount of tokenA to cancel //uint128 foreignBalance // amount of tokenA swapped by hashAddress (get by server-side) ) internal { require(msg.value >= IValidator(validator).getOracleFee(1), "Insufficient fee"); // check oracle fee for Cancel request address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver); uint256 pairID = getPairID[tokenA][tokenB]; require(pairID != 0, "Pair not exist"); if (cancelRequest[hashAddress].amount == 0) { // new cancel request uint256 balance = _balanceOf[hashAddress]; require(balance >= amountA && amountA != 0, "Wrong amount"); totalSupply[pairID] = totalSupply[pairID] - amountA; _balanceOf[hashAddress] = balance - amountA; } else { // repeat cancel request in case oracle issues. amountA = cancelRequest[hashAddress].amount; } cancelRequest[hashAddress] = Cancel(uint64(pairID), sender, amountA); // transfer fee to validator. May be changed to request tokens for compensation TransferHelper.safeTransferETH(feeReceiver, msg.value); if(contractSmart != address(0) && !isExcludedSender[sender]) { uint256 feeAmount = msg.value * cancelGasReimbursement / 100; if (feeAmount != 0) ISmart(contractSmart).requestCompensation(sender, feeAmount); } // request Oracle for fulfilled amount from hashAddress IValidator(validator).checkBalance(foreignFactory, hashAddress); emit CancelRequest(hashAddress, amountA); //emit CancelRequest(tokenA, tokenB, sender, receiver, amountA); } function _cancelApprove(address hashAddress, uint256 foreignBalance) internal { Cancel memory c = cancelRequest[hashAddress]; delete cancelRequest[hashAddress]; //require(c.foreignBalance == foreignBalance, "Oracle error"); uint256 balance = _balanceOf[hashAddress]; uint256 amount = uint256(c.amount); uint256 pairID = uint256(c.pairID); if (foreignBalance <= balance) { //approved - transfer token to its sender _transfer(getPairByID[pairID].tokenA, c.sender, amount); } else { //disapproved balance += amount; _balanceOf[hashAddress] = balance; totalSupply[pairID] += amount; } emit CancelApprove(hashAddress, balance); } function _claimTokenBehalf( address tokenA, // foreignToken address tokenB, // nativeToken address sender, address receiver, bool isInvestment, uint128 amountA, //amount of tokenA that has to be swapped uint128 currentRate, // rate with 18 decimals: tokenA price / tokenB price uint256 foreignBalance // total tokens amount sent bu user to pair on other chain // [1] foreignSpent, [2] nativeSpent, [3] nativeRate ) internal { uint256 pairID = getPairID[tokenB][tokenA]; // getPairID[nativeToken][foreignToken] require(pairID != 0, "Pair not exist"); // check rate uint256 diffRate = uint256(currentRate) * 100 / IValidator(validator).getRate(tokenB, tokenA); uint256 diffLimit = rateDiffLimit; require(diffRate >= 100 - diffLimit && diffRate <= 100 + diffLimit, "Wrong rate"); uint64 claimID; address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver); if (claimRequest[hashAddress].amount == 0) { // new claim request _balanceOf[hashAddress] += uint256(amountA); // total swapped amount of foreign token claimID = uint64(++claimIdCounter); } else { // repeat claim request in case oracle issues. claimID = claimRequest[hashAddress].claimID; if (amountA == 0) { // cancel claim request emit ClaimApprove(hashAddress, claimID, 0, 0, claimRequest[hashAddress].isInvestment); _balanceOf[hashAddress] = _balanceOf[hashAddress] - claimRequest[hashAddress].amount; delete claimRequest[hashAddress]; return; } amountA = claimRequest[hashAddress].amount; } address[] memory users = new address[](3); users[0] = hashAddress; users[1] = _getHashAddress(tokenA, tokenB, address(0), address(0)); // Native hash address on foreign chain users[2] = _getHashAddress(tokenB, tokenA, address(0), address(0)); // Foreign hash address on foreign chain claimRequest[hashAddress] = Claim(uint64(pairID), sender, receiver, claimID, isInvestment, amountA, currentRate, foreignBalance); IValidator(validator).checkBalances(foreignFactory, users); emit ClaimRequest(hashAddress, claimID, amountA, isInvestment); //emit ClaimRequest(tokenA, tokenB, sender, receiver, amountA); } // Approve or disapprove claim request. function _claimBehalfApprove( address hashAddress, uint256 foreignBalance, // total user's tokens balance on foreign chain uint256 foreignSpent, // total tokens spent by SmartSwap pair uint256 nativeEncoded // (nativeSpent, nativeRate) = _decode(nativeEncoded) ) internal { Claim memory c = claimRequest[hashAddress]; delete claimRequest[hashAddress]; //address hashSwap = _getHashAddress(getPairByID[c.pairID].tokenB, getPairByID[c.pairID].tokenA, c.sender, c.receiver); uint256 balance = _balanceOf[hashAddress]; // swapped amount of foreign tokens (include current claim amount) uint256 amount = uint256(c.amount); // amount of foreign token to swap require (amount != 0, "No active claim request"); require(foreignBalance == c.foreignBalance, "Oracle error"); uint256 nativeAmount; uint256 rest; if (foreignBalance >= balance) { //approve, user deposited not less foreign tokens then want to swap uint256 pairID = uint256(c.pairID); (uint256 nativeRate, uint256 nativeSpent) = _decode(nativeEncoded); (nativeAmount, rest) = _calculateAmount( pairID, amount, uint256(c.currentRate), foreignSpent, nativeSpent, nativeRate ); if (rest != 0) { _balanceOf[hashAddress] = balance - rest; // not all amount swapped amount = amount - rest; // swapped amount } require(totalSupply[pairID] >= nativeAmount, "Not enough Total Supply"); // may be commented totalSupply[pairID] = totalSupply[pairID] - nativeAmount; if (c.isInvestment) _contributeFromSmartSwap(getPairByID[pairID].tokenA, c.receiver, c.sender, nativeAmount); else _transfer(getPairByID[pairID].tokenA, c.receiver, nativeAmount); } else { //disapprove, discard claim _balanceOf[hashAddress] = balance - amount; amount = 0; } emit ClaimApprove(hashAddress, c.claimID, nativeAmount, amount, c.isInvestment); } // use structure to avoid stack too deep struct CalcVariables { // 18 decimals nominator with decimals converter: // Foreign = Native * Rate(18) / nominatorNativeToForeign uint256 nominatorForeignToNative; // 10**(18 + foreign decimals - native decimals) uint256 nominatorNativeToForeign; // 10**(18 + native decimals - foreign decimals) uint256 localNative; // already swapped Native tokens = _balanceOf[hashNative] uint256 localForeign; // already swapped Foreign tokens = decoded _balanceOf[hashForeign] uint256 localForeignRate; // Foreign token price / Native token price = decoded _balanceOf[hashForeign] address hashNative; // _getHashAddress(tokenA, tokenB, address(0), address(0)); address hashForeign; // _getHashAddress(tokenB, tokenA, address(0), address(0)); } function _calculateAmount( uint256 pairID, uint256 foreignAmount, uint256 rate, // Foreign token price / Native token price = (Native amount / Foreign amount) uint256 foreignSpent, // already swapped Foreign tokens (got from foreign contract) uint256 nativeSpent, // already swapped Native tokens (got from foreign contract) uint256 nativeRate // Native token price / Foreign token price. I.e. on BSC side: BNB price / ETH price = 0.2 ) internal returns(uint256 nativeAmount, uint256 rest) { CalcVariables memory vars; { address tokenA = getPairByID[pairID].tokenA; address tokenB = getPairByID[pairID].tokenB; uint256 nativeDecimals = decimals[tokenA]; uint256 foreignDecimals = decimals[tokenB]; vars.nominatorForeignToNative = 10**(18+foreignDecimals-nativeDecimals); vars.nominatorNativeToForeign = 10**(18+nativeDecimals-foreignDecimals); vars.hashNative = _getHashAddress(tokenA, tokenB, address(0), address(0)); vars.hashForeign = _getHashAddress(tokenB, tokenA, address(0), address(0)); vars.localNative = _balanceOf[vars.hashNative]; (vars.localForeignRate, vars.localForeign) = _decode(_balanceOf[vars.hashForeign]); } // step 1. Check is it enough unspent native tokens { require(nativeSpent >= vars.localNative, "NativeSpent balance higher then remote"); uint256 nativeAvailable = nativeSpent - vars.localNative; // nativeAvailable - amount ready to spend native tokens // nativeRate = Native token price / Foreign token price. I.e. on BSC side BNB price / ETH price = 0.2 if (nativeAvailable != 0) { // ? uint256 requireAmount = foreignAmount * vars.nominatorNativeToForeign / nativeRate; if (requireAmount <= nativeAvailable) { nativeAmount = requireAmount; // use already swapped tokens foreignAmount = 0; } else { nativeAmount = nativeAvailable; foreignAmount = (requireAmount - nativeAvailable) * nativeRate / vars.nominatorNativeToForeign; } _balanceOf[vars.hashNative] += nativeAmount; } } require(totalSupply[pairID] >= nativeAmount,"ERR: Not enough Total Supply"); // step 2. recalculate rate for swapped tokens if (foreignAmount != 0) { // i.e. on BSC side: rate = ETH price / BNB price = 5 uint256 requireAmount = foreignAmount * rate / vars.nominatorForeignToNative; if (totalSupply[pairID] < nativeAmount + requireAmount) { requireAmount = totalSupply[pairID] - nativeAmount; rest = foreignAmount - (requireAmount * vars.nominatorForeignToNative / rate); foreignAmount = foreignAmount - rest; } nativeAmount = nativeAmount + requireAmount; require(vars.localForeign >= foreignSpent, "ForeignSpent balance higher then local"); uint256 foreignAvailable = vars.localForeign - foreignSpent; // vars.localForeignRate, foreignAvailable - rate and amount swapped foreign tokens if (foreignAvailable != 0) { // recalculate avarage rate (native amount / foreign amount) rate = ((foreignAvailable * vars.localForeignRate) + (requireAmount * vars.nominatorForeignToNative)) / (foreignAvailable + foreignAmount); } _balanceOf[vars.hashForeign] = _encode(rate, vars.localForeign + foreignAmount); } } // transfer fee to receiver and request SMART token as compensation. // tokenA - token that user send // amount - amount of tokens that user send // user - address of user function _transferFee(address tokenA, uint256 amount, address user, address licensee) internal { require(licensee == address(0) || licenseeCompensator[licensee] != address(0), "licensee is not registered"); uint256 feeAmount = msg.value; uint256 compFee; // company fee if (tokenA < NATIVE_COINS) { require(feeAmount >= amount, "Insuficiant value"); // if native coin, then feeAmount = msg.value - swap amount feeAmount -= amount; compFee = amount * companyFee / 10000; // company fee } require(feeAmount >= processingFee, "Insufficient processing fee"); uint256 otherFee = feeAmount - processingFee; uint256 licenseeFeeAmount; uint256 licenseeFeeRate = licenseeFee[licensee]; if (licenseeFeeRate != 0 && otherFee != 0) { if (tokenA < NATIVE_COINS) { licenseeFeeAmount = amount * licenseeFeeRate / 10000; } else { licenseeFeeAmount = (otherFee * licenseeFeeRate)/(licenseeFeeRate + companyFee); } } require(otherFee >= compFee + licenseeFeeAmount, "Insuficiant fee"); feeAmount -= licenseeFeeAmount; if (licenseeFeeAmount != 0) { TransferHelper.safeTransferETH(licensee, licenseeFeeAmount); ISmart(licenseeCompensator[licensee]).requestCompensation(user, licenseeFeeAmount); } //TransferHelper.safeTransferETH(feeReceiver, feeAmount); collectedFees += feeAmount; if(contractSmart != address(0) && !isExcludedSender[msg.sender]) { feeAmount = ((feeAmount - processingFee) * companyFeeReimbursement + processingFee * swapGasReimbursement) / 100; if (feeAmount != 0) ISmart(contractSmart).requestCompensation(user, feeAmount); } } // contribute from SmartSwap on user behalf function _contributeFromSmartSwap(address token, address to, address user, uint256 value) internal { if (token < NATIVE_COINS) { IAuction(to).contributeFromSmartSwap{value: value}(payable(user)); } else { IERC20(token).approve(to, value); IAuction(to).contributeFromSmartSwap(token, value, user); } } // call appropriate transfer function function _transfer(address token, address to, uint256 value) internal { if (token < NATIVE_COINS) TransferHelper.safeTransferETH(to, value); else TransferHelper.safeTransfer(token, to, value); } // encode 64 bits of rate (decimal = 9). and 192 bits of amount // into uint256 where high 64 bits is rate and low 192 bit is amount // rate = foreign token price / native token price function _encode(uint256 rate, uint256 amount) internal pure returns(uint256 encodedBalance) { require(amount < MAX_AMOUNT, "Amount overflow"); require(rate < MAX_AMOUNT, "Rate overflow"); encodedBalance = rate * MAX_AMOUNT + amount; } // decode from uint256 where high 64 bits is rate and low 192 bit is amount // rate = foreign token price / native token price function _decode(uint256 encodedBalance) internal pure returns(uint256 rate, uint256 amount) { rate = encodedBalance / MAX_AMOUNT; amount = uint128(encodedBalance); } function _getHashAddress( address tokenA, address tokenB, address sender, address receiver ) internal pure returns (address) { return address(uint160(uint256(keccak256(abi.encodePacked(tokenA, tokenB, sender, receiver))))); } }
percentage of company Fee Reimbursement by SMART tokens
uint256 public companyFeeReimbursement;
285,013
[ 1, 18687, 434, 9395, 30174, 868, 381, 70, 295, 307, 475, 635, 12014, 4928, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 9395, 14667, 426, 381, 70, 295, 307, 475, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xff6609E258267567F168105190cF8935f6229cD1/sources/PengyPresaleMainnet.sol
Variables visibility is private, we are fetching them with the getters to optimise gas usage We are using ether because the token has 18 decimals We're using those in frontend to show the contributions per tier
contract PengyPresaleMainnet { address public immutable tokenAddress; address public immutable owner; address public constant ethWithdrawDestination = 0xe7bE0E9c3a5650dB004E306FC9D9cCE97eEe7166; uint256 private constant tiersCooldown = 10 minutes; uint256 private tierOneStartTimestamp; uint256 private tierOneEndTimestamp; uint256 private tierTwoStartTimestamp; uint256 private tierTwoEndTimestamp; uint256 private tierThreeStartTimestamp; uint256 private tierThreeEndTimestamp; uint256 private tierOneEthAllocated = 10 ether; uint256 private tierTwoEthAllocated = 10 ether; uint256 private tierThreeEthAllocated = 10 ether; uint256 private hardcap = tierOneEthAllocated + tierTwoEthAllocated + tierThreeEthAllocated; uint256 private maximumContribution = 0.2 ether; uint256 private tierOneTokensAllocated = 0; uint256 private tierTwoTokensAllocated = 0; uint256 private tierThreeTokensAllocated = 0; uint256 private constant totalTokensForSale = 1_920_000_000 ether; bytes32 private merkleRootTierOne; bytes32 private merkleRootTierTwo; bytes32 private merkleRootTierThree; mapping(address => uint256) public boughtTokens; mapping(address => uint256) public contribution; uint256 contributionsTierOne; uint256 contributionsTierTwo; uint256 contributionsTierThree; uint256 public totalContributions = 0; address[] public buyers; address public constant DEAD = 0x000000000000000000000000000000000000dEaD; bool private poolsFunded = false; event TokensBought(address indexed buyer, uint256 amount); event EtherWithdrawn(address indexed withdrawer, uint256 amount); event PoolsFunded( uint256 amountInTierOne, uint256 amountInTierTwo, uint256 amountInTierThree ); event TokensBurned(uint256 amount); event TokensAirdropped(address indexed recipient, uint256 amount); event TimestampsChanged( uint256[2] tierOne, uint256[2] tierTwo, uint256[2] tierThree ); event MerkleRootsChanged( bytes32 merkleRootTierOne, bytes32 merkleRootTierTwo, bytes32 merkleRootTierThree ); modifier onlyOwner() { if (msg.sender != owner) { revert SenderNotContractOwner(); } _; } constructor( bytes32 _merkleRootTierOne, bytes32 _merkleRootTierTwo, bytes32 _merkleRootTierThree, address _tokenAddress, uint256 _startTimestamp modifier onlyOwner() { if (msg.sender != owner) { revert SenderNotContractOwner(); } _; } constructor( bytes32 _merkleRootTierOne, bytes32 _merkleRootTierTwo, bytes32 _merkleRootTierThree, address _tokenAddress, uint256 _startTimestamp ) payable { owner = msg.sender; tokenAddress = _tokenAddress; merkleRootTierOne = _merkleRootTierOne; merkleRootTierTwo = _merkleRootTierTwo; merkleRootTierThree = _merkleRootTierThree; tierOneStartTimestamp = _startTimestamp; tierOneEndTimestamp = tierOneStartTimestamp + tiersCooldown; tierTwoStartTimestamp = tierOneEndTimestamp; tierTwoEndTimestamp = tierTwoStartTimestamp + tiersCooldown; tierThreeStartTimestamp = tierTwoEndTimestamp; tierThreeEndTimestamp = tierThreeStartTimestamp + tiersCooldown; } function getTiersContributions() public view returns (uint256, uint256, uint256) { return ( contributionsTierOne, contributionsTierTwo, contributionsTierThree ); } function getMerkleRoots() public view returns (bytes32, bytes32, bytes32) { return (merkleRootTierOne, merkleRootTierTwo, merkleRootTierThree); } function getTierEtherAllocated() public view returns (uint256, uint256, uint256) { return ( tierOneEthAllocated, tierTwoEthAllocated, tierThreeEthAllocated ); } function getTierTokenAllocated() public view returns (uint256, uint256, uint256) { return ( tierOneTokensAllocated, tierTwoTokensAllocated, tierThreeTokensAllocated ); } function getTimestamps() public view returns (uint256[2] memory, uint256[2] memory, uint256[2] memory) { return ( [tierOneStartTimestamp, tierOneEndTimestamp], [tierTwoStartTimestamp, tierTwoEndTimestamp], [tierThreeStartTimestamp, tierThreeEndTimestamp] ); } function getMerkleRootForCurrentTier() internal view returns (bytes32) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return merkleRootTierOne; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return merkleRootTierTwo; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return merkleRootTierThree; revert NoTierActive(); } } function getMerkleRootForCurrentTier() internal view returns (bytes32) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return merkleRootTierOne; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return merkleRootTierTwo; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return merkleRootTierThree; revert NoTierActive(); } } function getMerkleRootForCurrentTier() internal view returns (bytes32) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return merkleRootTierOne; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return merkleRootTierTwo; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return merkleRootTierThree; revert NoTierActive(); } } function getMerkleRootForCurrentTier() internal view returns (bytes32) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return merkleRootTierOne; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return merkleRootTierTwo; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return merkleRootTierThree; revert NoTierActive(); } } } else { function getAvailableTokensAndEthForCurrentTier() public view returns (uint256 availableEth, uint256 availableTokens) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return (tierOneEthAllocated, tierOneTokensAllocated); } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated ); } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated + tierThreeEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated + tierThreeTokensAllocated ); revert NoTierActive(); } } function getAvailableTokensAndEthForCurrentTier() public view returns (uint256 availableEth, uint256 availableTokens) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return (tierOneEthAllocated, tierOneTokensAllocated); } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated ); } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated + tierThreeEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated + tierThreeTokensAllocated ); revert NoTierActive(); } } function getAvailableTokensAndEthForCurrentTier() public view returns (uint256 availableEth, uint256 availableTokens) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return (tierOneEthAllocated, tierOneTokensAllocated); } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated ); } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated + tierThreeEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated + tierThreeTokensAllocated ); revert NoTierActive(); } } function getAvailableTokensAndEthForCurrentTier() public view returns (uint256 availableEth, uint256 availableTokens) { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { return (tierOneEthAllocated, tierOneTokensAllocated); } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated ); } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp ) { return ( tierOneEthAllocated + tierTwoEthAllocated + tierThreeEthAllocated, tierOneTokensAllocated + tierTwoTokensAllocated + tierThreeTokensAllocated ); revert NoTierActive(); } } } else { function fundTokenPools() external onlyOwner { if (poolsFunded == true) { revert PoolsAlreadyFunded(); } msg.sender, address(this), totalTokensForSale ); uint256 tokensPerOnePool = totalTokensForSale / 3; tierTwoTokensAllocated = tokensPerOnePool; tierThreeTokensAllocated = tokensPerOnePool; poolsFunded = true; emit PoolsFunded( tierOneTokensAllocated, tierTwoTokensAllocated, tierThreeTokensAllocated ); } function fundTokenPools() external onlyOwner { if (poolsFunded == true) { revert PoolsAlreadyFunded(); } msg.sender, address(this), totalTokensForSale ); uint256 tokensPerOnePool = totalTokensForSale / 3; tierTwoTokensAllocated = tokensPerOnePool; tierThreeTokensAllocated = tokensPerOnePool; poolsFunded = true; emit PoolsFunded( tierOneTokensAllocated, tierTwoTokensAllocated, tierThreeTokensAllocated ); } IERC20(tokenAddress).transferFrom( tierOneTokensAllocated = tokensPerOnePool; function adjustPoolsInCaseOfUndersale() internal { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp && tierOneEthAllocated != 0 && tierOneTokensAllocated != 0 ) { } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp && tierTwoEthAllocated != 0 && tierTwoTokensAllocated != 0 ) { tierTwoEthAllocated += tierOneEthAllocated; tierTwoTokensAllocated += tierOneTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp && tierThreeEthAllocated != 0 && tierThreeTokensAllocated != 0 ) { tierThreeEthAllocated += tierOneEthAllocated; tierThreeEthAllocated += tierTwoEthAllocated; tierThreeTokensAllocated += tierOneTokensAllocated; tierThreeTokensAllocated += tierTwoTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; tierTwoEthAllocated = 0; tierTwoTokensAllocated = 0; } } function adjustPoolsInCaseOfUndersale() internal { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp && tierOneEthAllocated != 0 && tierOneTokensAllocated != 0 ) { } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp && tierTwoEthAllocated != 0 && tierTwoTokensAllocated != 0 ) { tierTwoEthAllocated += tierOneEthAllocated; tierTwoTokensAllocated += tierOneTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp && tierThreeEthAllocated != 0 && tierThreeTokensAllocated != 0 ) { tierThreeEthAllocated += tierOneEthAllocated; tierThreeEthAllocated += tierTwoEthAllocated; tierThreeTokensAllocated += tierOneTokensAllocated; tierThreeTokensAllocated += tierTwoTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; tierTwoEthAllocated = 0; tierTwoTokensAllocated = 0; } } function adjustPoolsInCaseOfUndersale() internal { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp && tierOneEthAllocated != 0 && tierOneTokensAllocated != 0 ) { } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp && tierTwoEthAllocated != 0 && tierTwoTokensAllocated != 0 ) { tierTwoEthAllocated += tierOneEthAllocated; tierTwoTokensAllocated += tierOneTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp && tierThreeEthAllocated != 0 && tierThreeTokensAllocated != 0 ) { tierThreeEthAllocated += tierOneEthAllocated; tierThreeEthAllocated += tierTwoEthAllocated; tierThreeTokensAllocated += tierOneTokensAllocated; tierThreeTokensAllocated += tierTwoTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; tierTwoEthAllocated = 0; tierTwoTokensAllocated = 0; } } function adjustPoolsInCaseOfUndersale() internal { if ( block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp && tierOneEthAllocated != 0 && tierOneTokensAllocated != 0 ) { } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp && tierTwoEthAllocated != 0 && tierTwoTokensAllocated != 0 ) { tierTwoEthAllocated += tierOneEthAllocated; tierTwoTokensAllocated += tierOneTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp <= tierThreeEndTimestamp && tierThreeEthAllocated != 0 && tierThreeTokensAllocated != 0 ) { tierThreeEthAllocated += tierOneEthAllocated; tierThreeEthAllocated += tierTwoEthAllocated; tierThreeTokensAllocated += tierOneTokensAllocated; tierThreeTokensAllocated += tierTwoTokensAllocated; tierOneEthAllocated = 0; tierOneTokensAllocated = 0; tierTwoEthAllocated = 0; tierTwoTokensAllocated = 0; } } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } uint256 tokensBoughtThisTx = ((availableTokens * msg.value) / function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } if ( function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function buy(bytes32[] memory proof) external payable { adjustPoolsInCaseOfUndersale(); bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(msg.sender, 0))) ); if (contribution[msg.sender] + msg.value > maximumContribution) { revert ContributionExceedsMaximumAllowed(); } if (!MerkleProof.verify(proof, getMerkleRootForCurrentTier(), leaf)) { revert NotWhitelisted(); } if (block.timestamp < tierOneStartTimestamp) { revert IDONotStarted(); } if (block.timestamp > tierThreeEndTimestamp) { revert IDOEnded(); } if (boughtTokens[msg.sender] == 0) { buyers.push(msg.sender); } ( uint256 availableEth, uint256 availableTokens ) = getAvailableTokensAndEthForCurrentTier(); if (availableEth == 0 || availableTokens == 0) { revert TierHasSoldOut(); } availableEth); boughtTokens[msg.sender] += tokensBoughtThisTx; contribution[msg.sender] += msg.value; totalContributions += msg.value; if (totalContributions > hardcap) { revert HardcapReached(); } block.timestamp >= tierOneStartTimestamp && block.timestamp < tierOneEndTimestamp ) { tierOneEthAllocated -= msg.value; tierOneTokensAllocated -= tokensBoughtThisTx; contributionsTierOne += msg.value; } else if ( block.timestamp >= tierTwoStartTimestamp && block.timestamp < tierTwoEndTimestamp ) { tierTwoEthAllocated -= msg.value; tierTwoTokensAllocated -= tokensBoughtThisTx; contributionsTierTwo += msg.value; } else if ( block.timestamp >= tierThreeStartTimestamp && block.timestamp < tierThreeEndTimestamp ) { tierThreeEthAllocated -= msg.value; tierThreeTokensAllocated -= tokensBoughtThisTx; contributionsTierThree += msg.value; } emit TokensBought(msg.sender, tokensBoughtThisTx); } function withdrawEth() external { if (block.timestamp < tierThreeEndTimestamp) { revert CannotWithdrawETHWithActiveIDO(); } uint256 etherToWithdraw = address(this).balance; (bool success, ) = address(ethWithdrawDestination).call{ value: etherToWithdraw }(""); if (!success) { revert WithdrawFailed(); } emit EtherWithdrawn(ethWithdrawDestination, etherToWithdraw); } function withdrawEth() external { if (block.timestamp < tierThreeEndTimestamp) { revert CannotWithdrawETHWithActiveIDO(); } uint256 etherToWithdraw = address(this).balance; (bool success, ) = address(ethWithdrawDestination).call{ value: etherToWithdraw }(""); if (!success) { revert WithdrawFailed(); } emit EtherWithdrawn(ethWithdrawDestination, etherToWithdraw); } function withdrawEth() external { if (block.timestamp < tierThreeEndTimestamp) { revert CannotWithdrawETHWithActiveIDO(); } uint256 etherToWithdraw = address(this).balance; (bool success, ) = address(ethWithdrawDestination).call{ value: etherToWithdraw }(""); if (!success) { revert WithdrawFailed(); } emit EtherWithdrawn(ethWithdrawDestination, etherToWithdraw); } function withdrawEth() external { if (block.timestamp < tierThreeEndTimestamp) { revert CannotWithdrawETHWithActiveIDO(); } uint256 etherToWithdraw = address(this).balance; (bool success, ) = address(ethWithdrawDestination).call{ value: etherToWithdraw }(""); if (!success) { revert WithdrawFailed(); } emit EtherWithdrawn(ethWithdrawDestination, etherToWithdraw); } function changeStartTimestamp(uint256 _startTimestamp) external onlyOwner { if (block.timestamp > tierOneStartTimestamp) { revert CannotChangeDatesIfIDOStarted(); } tierOneStartTimestamp = _startTimestamp; tierOneEndTimestamp = tierOneStartTimestamp + tiersCooldown; tierTwoStartTimestamp = tierOneEndTimestamp; tierTwoEndTimestamp = tierTwoStartTimestamp + tiersCooldown; tierThreeStartTimestamp = tierTwoEndTimestamp; tierThreeEndTimestamp = tierThreeStartTimestamp + tiersCooldown; emit TimestampsChanged( [tierOneStartTimestamp, tierOneEndTimestamp], [tierTwoStartTimestamp, tierTwoEndTimestamp], [tierThreeStartTimestamp, tierThreeEndTimestamp] ); } function changeStartTimestamp(uint256 _startTimestamp) external onlyOwner { if (block.timestamp > tierOneStartTimestamp) { revert CannotChangeDatesIfIDOStarted(); } tierOneStartTimestamp = _startTimestamp; tierOneEndTimestamp = tierOneStartTimestamp + tiersCooldown; tierTwoStartTimestamp = tierOneEndTimestamp; tierTwoEndTimestamp = tierTwoStartTimestamp + tiersCooldown; tierThreeStartTimestamp = tierTwoEndTimestamp; tierThreeEndTimestamp = tierThreeStartTimestamp + tiersCooldown; emit TimestampsChanged( [tierOneStartTimestamp, tierOneEndTimestamp], [tierTwoStartTimestamp, tierTwoEndTimestamp], [tierThreeStartTimestamp, tierThreeEndTimestamp] ); } function airdropContributors( uint256 buyerCountToAirdrop ) external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotAirdropWithActiveIDO(); } uint256 amountToAirdrop; if (buyerCountToAirdrop > buyers.length) { amountToAirdrop = buyers.length; amountToAirdrop = buyerCountToAirdrop; } for (uint256 i = 0; i < amountToAirdrop; i++) { address buyer = buyers[buyers.length - 1]; uint256 tokens = boughtTokens[buyer]; buyers.pop(); IERC20(tokenAddress).transfer(buyer, tokens); emit TokensAirdropped(buyer, tokens); } } function airdropContributors( uint256 buyerCountToAirdrop ) external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotAirdropWithActiveIDO(); } uint256 amountToAirdrop; if (buyerCountToAirdrop > buyers.length) { amountToAirdrop = buyers.length; amountToAirdrop = buyerCountToAirdrop; } for (uint256 i = 0; i < amountToAirdrop; i++) { address buyer = buyers[buyers.length - 1]; uint256 tokens = boughtTokens[buyer]; buyers.pop(); IERC20(tokenAddress).transfer(buyer, tokens); emit TokensAirdropped(buyer, tokens); } } function airdropContributors( uint256 buyerCountToAirdrop ) external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotAirdropWithActiveIDO(); } uint256 amountToAirdrop; if (buyerCountToAirdrop > buyers.length) { amountToAirdrop = buyers.length; amountToAirdrop = buyerCountToAirdrop; } for (uint256 i = 0; i < amountToAirdrop; i++) { address buyer = buyers[buyers.length - 1]; uint256 tokens = boughtTokens[buyer]; buyers.pop(); IERC20(tokenAddress).transfer(buyer, tokens); emit TokensAirdropped(buyer, tokens); } } } else { function airdropContributors( uint256 buyerCountToAirdrop ) external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotAirdropWithActiveIDO(); } uint256 amountToAirdrop; if (buyerCountToAirdrop > buyers.length) { amountToAirdrop = buyers.length; amountToAirdrop = buyerCountToAirdrop; } for (uint256 i = 0; i < amountToAirdrop; i++) { address buyer = buyers[buyers.length - 1]; uint256 tokens = boughtTokens[buyer]; buyers.pop(); IERC20(tokenAddress).transfer(buyer, tokens); emit TokensAirdropped(buyer, tokens); } } function changeMerkleRoots( bytes32 _merkleRootTierOne, bytes32 _merkleRootTierTwo, bytes32 _merkleRootTierThree ) external onlyOwner { merkleRootTierOne = _merkleRootTierOne; merkleRootTierTwo = _merkleRootTierTwo; merkleRootTierThree = _merkleRootTierThree; emit MerkleRootsChanged( merkleRootTierOne, merkleRootTierTwo, merkleRootTierThree ); } function burnUnsoldTokens() external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotBurnTokensWithActiveIDO(); } if (buyers.length > 0) { revert CannotBurnTokensWithActiveIDO(); } DEAD, IERC20(tokenAddress).balanceOf(address(this)) ); emit TokensBurned(IERC20(tokenAddress).balanceOf(address(this))); } function burnUnsoldTokens() external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotBurnTokensWithActiveIDO(); } if (buyers.length > 0) { revert CannotBurnTokensWithActiveIDO(); } DEAD, IERC20(tokenAddress).balanceOf(address(this)) ); emit TokensBurned(IERC20(tokenAddress).balanceOf(address(this))); } function burnUnsoldTokens() external onlyOwner { if (block.timestamp < tierThreeEndTimestamp) { revert CannotBurnTokensWithActiveIDO(); } if (buyers.length > 0) { revert CannotBurnTokensWithActiveIDO(); } DEAD, IERC20(tokenAddress).balanceOf(address(this)) ); emit TokensBurned(IERC20(tokenAddress).balanceOf(address(this))); } IERC20(tokenAddress).transfer( }
2,845,942
[ 1, 6158, 9478, 353, 3238, 16, 732, 854, 16191, 2182, 598, 326, 23849, 358, 5213, 784, 16189, 4084, 1660, 854, 1450, 225, 2437, 2724, 326, 1147, 711, 6549, 15105, 1660, 4565, 1450, 5348, 316, 15442, 358, 2405, 326, 13608, 6170, 1534, 17742, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 453, 275, 7797, 12236, 5349, 6376, 2758, 288, 203, 565, 1758, 1071, 11732, 1147, 1887, 31, 203, 565, 1758, 1071, 11732, 3410, 31, 203, 203, 565, 1758, 1071, 5381, 13750, 1190, 9446, 5683, 273, 203, 3639, 374, 6554, 27, 70, 41, 20, 41, 29, 71, 23, 69, 4313, 3361, 72, 38, 26565, 41, 29490, 4488, 29, 40, 29, 71, 1441, 10580, 73, 41, 73, 27, 23553, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 11374, 414, 39, 1371, 2378, 273, 1728, 6824, 31, 203, 203, 565, 2254, 5034, 3238, 17742, 3335, 1685, 4921, 31, 203, 565, 2254, 5034, 3238, 17742, 3335, 1638, 4921, 31, 203, 203, 565, 2254, 5034, 3238, 17742, 11710, 1685, 4921, 31, 203, 565, 2254, 5034, 3238, 17742, 11710, 1638, 4921, 31, 203, 203, 565, 2254, 5034, 3238, 17742, 28019, 1685, 4921, 31, 203, 565, 2254, 5034, 3238, 17742, 28019, 1638, 4921, 31, 203, 203, 565, 2254, 5034, 3238, 17742, 3335, 41, 451, 29392, 273, 1728, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 17742, 11710, 41, 451, 29392, 273, 1728, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 17742, 28019, 41, 451, 29392, 273, 1728, 225, 2437, 31, 203, 203, 565, 2254, 5034, 3238, 7877, 5909, 273, 203, 3639, 17742, 3335, 41, 451, 29392, 397, 17742, 11710, 41, 451, 29392, 397, 17742, 28019, 41, 451, 29392, 31, 203, 203, 565, 2254, 5034, 3238, 4207, 442, 4027, 273, 374, 18, 22, 225, 2437, 31, 203, 203, 565, 2254, 5034, 3238, 17742, 3335, 5157, 29392, 273, 374, 31, 203, 565, 2254, 2 ]
./partial_match/100/0x3E5d55162db958E6C00c59a6e81587C153E18f7b/sources/GenuNFT_STAGE.sol
* @notice Check if caller is the owner or a creator branf/
function _isGenuinoOrCreatorBrand(uint256 tokenId) internal view { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); bool isCreator = _brandIds[msg.sender] != 0 && tokenCreatedBy[tokenId] == _brandIds[msg.sender]; require(msg.sender == _owner || isCreator); }
16,680,411
[ 1, 1564, 309, 4894, 353, 326, 3410, 578, 279, 11784, 324, 2450, 74, 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, 225, 445, 389, 291, 43, 2104, 15020, 1162, 10636, 20484, 12, 11890, 5034, 1147, 548, 13, 2713, 1476, 288, 203, 565, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 30, 3726, 843, 364, 1661, 19041, 1147, 8863, 203, 565, 1426, 353, 10636, 273, 389, 20523, 2673, 63, 3576, 18, 15330, 65, 480, 374, 597, 1147, 6119, 858, 63, 2316, 548, 65, 422, 389, 20523, 2673, 63, 3576, 18, 15330, 15533, 203, 565, 2583, 12, 3576, 18, 15330, 422, 389, 8443, 747, 353, 10636, 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/41/0x53b2c9C0f7F8eC94832D145FaaC8ec104286B0C9/sources/contracts/LpFeeSplitter.sol
@dev Swap a given token amountIn to the configured reward token
function _toRewards(address token, uint256 amountIn) internal returns (uint256 amountOut) { amountOut = _swap(token, rewardsToken, amountIn, address(this)); }
16,377,500
[ 1, 12521, 279, 864, 1147, 3844, 382, 358, 326, 4351, 19890, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 869, 17631, 14727, 12, 2867, 1147, 16, 2254, 5034, 3844, 382, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 11890, 5034, 3844, 1182, 13, 203, 565, 288, 203, 3639, 3844, 1182, 273, 389, 22270, 12, 2316, 16, 283, 6397, 1345, 16, 3844, 382, 16, 1758, 12, 2211, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: LicenseRef-StarterLabs-Business-Source /* ----------------------------------------------------------------------------- The Licensed Work is (c) 2022 Starter Labs, LLC Licensor: Starter Labs, LLC Licensed Work: OpenStarter v1 Effective Date: 2022 March 1 Full License Text: https://github.com/StarterXyz/LICENSE ----------------------------------------------------------------------------- */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./lib/Ownable.sol"; import "./lib/SafeMath.sol"; import "./lib/ERC20.sol"; interface IOpenStarterStaking { function accounts(address) external view returns ( uint256[15] memory, uint256, uint256, uint256 ); function getUserBalances(address) external view returns (uint256[] memory); function getStakerTier(address) external view returns (uint256); } interface IExternalStaking { function balanceOf(address) external view returns (uint256); } contract OpenStarterLibrary is Ownable { using SafeMath for uint256; uint256[15][10] private tiers; // tiers[0][] is APE; tiers[1][] is START; // Archeologist: 20K+ START OR 10K APE for 14+ days // Conservator: 10K+ START OR 1K APE for 10+ days // Researcher: 1K+ START OR 100 APE for 7+ days // Navigator: 100+ START OR 10 APE for 5+ days // Lottery: <Navigator or no staking at all mapping(address => bool) private starterDevs; IOpenStarterStaking public openStarterStakingPool; IExternalStaking public externalStaking; address private nftFactoryAddress; address private saleFactoryAddress; address private vaultFactoryAddress; address[] public nfts; address[] public sales; uint256 private devFeePercentage = 10; // 10% dev fee for INOs address private WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 private allocationCount = 4; uint256[] private allocationPercentage = [5, 10, 20, 30, 35]; uint256[] private allocationTime = [30 * 60, 60 * 60, 90 * 60, 120 * 60]; uint256[15] private minVoterBalance = [ 10 * 1e18, 100 * 1e18, 100000 * 1e18 ]; // min APE needed to vote uint256[15] private minYesVotesThreshold = [ 10000000 * 1e18, 100000 * 1e18, 100000000000 * 1e18 ]; // min YES votes needed to pass uint256 private externalTokenIndex = 0; string public featured; // ipfs link for featured projects list string public upcomings; // ipfs link for upcoming projects list string public finished; // ipfs link for finished projects list constructor(address _openStarterStakingPool, address _externalStaking) public { openStarterStakingPool = IOpenStarterStaking(_openStarterStakingPool); externalStaking = IExternalStaking(_externalStaking); starterDevs[address(0xf7e925818a20E5573Ee0f3ba7aBC963e17f2c476)] = true; starterDevs[address(0x283B3b8f340E8FB94D55b17E906744a74074cD07)] = true; tiers[0][0] = 10 * 1e18; // tiers: 10+ APE, 100+ APE, 1K+ APE, 10K+ APE tiers[0][1] = 100 * 1e18; tiers[0][2] = 1000 * 1e18; tiers[0][3] = 10000 * 1e18; tiers[1][0] = 100 * 1e18; // tiers: 100+ START, 1K+ START, 10K+ START, 20K+ START tiers[1][1] = 1000 * 1e18; tiers[1][2] = 10000 * 1e18; tiers[1][3] = 20000 * 1e18; } modifier onlyStarterDev() { require( owner == msg.sender || starterDevs[msg.sender], "onlyStarterDev" ); _; } modifier onlyFactory() { require( owner == msg.sender || starterDevs[msg.sender] || nftFactoryAddress == msg.sender || saleFactoryAddress == msg.sender, "onlyFactory" ); _; } function getTier(uint256 tokenIndex, uint256 tierIndex) external view returns (uint256) { return tiers[tokenIndex][tierIndex]; } function setTier( uint256 tokenIndex, uint256 tierIndex, uint256 _value ) external onlyStarterDev { tiers[tokenIndex][tierIndex] = _value; } function getUserTier(uint256 stakingTokenIndex, uint256 amount) external view returns (uint256) { uint256 i = 0; uint256 tier = 0; uint256 tiersLen = tiers[stakingTokenIndex].length; for (i = 0; i < tiersLen; i++) { if ( amount >= tiers[stakingTokenIndex][i] && tiers[stakingTokenIndex][i] > 0 ) { tier = i + 1; } else { break; } } return tier; } function getStarterDev(address _dev) external view returns (bool) { return starterDevs[_dev]; } function setStarterDevAddress(address _newDev) external onlyOwner { starterDevs[_newDev] = true; } function removeStarterDevAddress(address _oldDev) external onlyOwner { starterDevs[_oldDev] = false; } function getNftFactoryAddress() external view returns (address) { return nftFactoryAddress; } function setNftFactoryAddress(address _newFactoryAddress) external onlyStarterDev { nftFactoryAddress = _newFactoryAddress; } function getSaleFactoryAddress() external view returns (address) { return saleFactoryAddress; } function setSaleFactoryAddress(address _newFactoryAddress) external onlyStarterDev { saleFactoryAddress = _newFactoryAddress; } function getVaultFactoryAddress() external view returns (address) { return vaultFactoryAddress; } function setVaultFactoryAddress(address _newFactoryAddress) external onlyStarterDev { vaultFactoryAddress = _newFactoryAddress; } function addNfts(address _nftAddress) external onlyFactory returns (uint256) { nfts.push(_nftAddress); return nfts.length - 1; } function addSaleAddress(address _saleAddress) external onlyFactory returns (uint256) { sales.push(_saleAddress); return sales.length - 1; } function addSales(address[] calldata _saleAddresses) external onlyFactory { uint256 salesLen = _saleAddresses.length; for (uint256 i = 0; i < salesLen; i++) { sales.push(_saleAddresses[i]); } } function setNftAddress(uint256 _index, address _nftAddress) external onlyFactory { nfts[_index] = _nftAddress; } function setSaleAddress(uint256 _index, address _saleAddress) external onlyFactory { sales[_index] = _saleAddress; } function getStakingPool() external view returns (address) { return address(openStarterStakingPool); } function setStakingPool(address _openStarterStakingPool) external onlyStarterDev { openStarterStakingPool = IOpenStarterStaking(_openStarterStakingPool); } function getExternalStaking() external view returns (address) { return address(externalStaking); } function setExternalStaking(address _openStarterStakingPool) external onlyStarterDev { externalStaking = IExternalStaking(_openStarterStakingPool); } function getNftsCount() external view returns (uint256) { return nfts.length; } function getNftAddress(uint256 nftId) external view returns (address) { return nfts[nftId]; } function getSalesCount() external view returns (uint256) { return sales.length; } function getSaleAddress(uint256 saleId) external view returns (address) { return sales[saleId]; } function getDevFeePercentage() external view returns (uint256) { return devFeePercentage; } function setDevFeePercentage(uint256 _devFeePercentage) external onlyStarterDev { devFeePercentage = _devFeePercentage; } function getWETH() external view returns (address) { return WETH; } function setWETH(address _WETH) external onlyStarterDev { WETH = _WETH; } function getAllocationCount() external view returns (uint256) { return allocationCount; } function setAllocationCount(uint256 _count) external onlyStarterDev { allocationCount = _count; } function getAllocationPercentage(uint256 _index) external view returns (uint256) { return allocationPercentage[_index]; } function setAllocationPercentage(uint256 _index, uint256 _value) external onlyStarterDev { allocationPercentage[_index] = _value; } function getAllocationTime(uint256 _index) external view returns (uint256) { return allocationTime[_index]; } function setAllocationTime(uint256 _index, uint256 _value) external onlyStarterDev { allocationTime[_index] = _value; } function getStaked(address _sender, uint256 _voteTokenIndex) external view returns (uint256) { uint256[] memory balances = openStarterStakingPool.getUserBalances( _sender ); uint256 externalBalance = 0; if ( address(externalStaking) != 0x0000000000000000000000000000000000000000 && _voteTokenIndex == externalTokenIndex // only include outside bal if its the votetoken ) { externalBalance = externalStaking.balanceOf(_sender); } return balances[_voteTokenIndex] + externalBalance; } function getStakerTier(address _staker) external view returns (uint256) { return openStarterStakingPool.getStakerTier(_staker); } function getMinVoterBalance(uint256 _voteTokenIndex) external view returns (uint256) { return minVoterBalance[_voteTokenIndex]; } function setMinVoterBalance(uint256 _voteTokenIndex, uint256 _balance) external onlyStarterDev { minVoterBalance[_voteTokenIndex] = _balance; } function getMinYesVotesThreshold(uint256 _voteTokenIndex) external view returns (uint256) { return minYesVotesThreshold[_voteTokenIndex]; } function setMinYesVotesThreshold(uint256 _voteTokenIndex, uint256 _balance) external onlyStarterDev { minYesVotesThreshold[_voteTokenIndex] = _balance; } function getTierByTime(uint256 _openTime, uint256 _currentTimestamp) external view returns (uint256) { if ( _currentTimestamp >= _openTime && _currentTimestamp <= _openTime + allocationTime[0] ) { return 4; } for (uint256 i = 0; i < allocationCount - 1; i++) { if ( _currentTimestamp > _openTime + allocationTime[i] && _currentTimestamp <= _openTime + allocationTime[i + 1] ) { return allocationCount - i - 1; } } return 0; } function setFeaturedProjects(string memory _url) external onlyStarterDev { featured = _url; } function setUpcomingProjects(string memory _url) external onlyStarterDev { upcomings = _url; } function setFinishedProjects(string memory _url) external onlyStarterDev { finished = _url; } function getExternalTokenIndex() external view returns (uint256) { return externalTokenIndex; } function setExternalTokenIndex(uint256 _index) external onlyStarterDev { externalTokenIndex = _index; } function getExternalStaked(uint256 tokenIndex, address _staker) external view returns (uint256) { if (tokenIndex != externalTokenIndex) return 0; if ( address(externalStaking) == 0x0000000000000000000000000000000000000000 ) return 0; return externalStaking.balanceOf(_staker); } } // 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Owned * @dev Basic contract for authorization control. * @author dicether */ contract Ownable { address public owner; address public pendingOwner; event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner); event LogOwnerShipTransferInitiated(address indexed previousOwner, address indexed newOwner); /** * @dev Modifier, which throws if called by other account than owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Set contract creator as initial owner */ constructor() public { owner = msg.sender; pendingOwner = address(0); } /** * @dev Allows the current owner to set the pendingOwner address. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { pendingOwner = _newOwner; emit LogOwnerShipTransferInitiated(owner, _newOwner); } /** * @dev PendingOwner can accept ownership. */ function claimOwnership() public onlyPendingOwner { owner = pendingOwner; pendingOwner = address(0); emit LogOwnerShipTransferred(owner, pendingOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./Address.sol"; import "./Context.sol"; import "./SafeMath.sol"; import "../interfaces/IERC20.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; uint256 _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @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 Set contract creator as initial owner/
constructor() public { owner = msg.sender; pendingOwner = address(0); }
206,458
[ 1, 694, 6835, 11784, 487, 2172, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 4634, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7EEFee2d0B0e23b7Ce6B56a9cE9B62A599e6E9Da/sources/contracts/ArcadeGlyphs.sol
-- Public interface
function alreadyMinted(string memory name) external view returns (uint _count) { Game storage game = gameNameToGame[name]; return game.counter.current() - game.startTokenId; }
9,785,413
[ 1, 413, 7224, 1560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1818, 49, 474, 329, 12, 1080, 3778, 508, 13, 3903, 1476, 1135, 261, 11890, 389, 1883, 13, 288, 203, 3639, 14121, 2502, 7920, 273, 7920, 28455, 12496, 63, 529, 15533, 203, 3639, 327, 7920, 18, 7476, 18, 2972, 1435, 300, 7920, 18, 1937, 1345, 548, 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 ]
pragma solidity ^0.5.17; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } contract ERC20 is IERC20 { using SafeMath for uint256; // mapping (address => uint256) private _balances; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(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 { 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); _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 Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `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, msg.sender, _allowances[account][msg.sender].sub(amount)); } } library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } 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), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } 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) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract ERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct lockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => lockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ // function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); function lock(bytes32 _reason, uint256 _amount, uint256 _time, address _of) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } //Coin contract contract AIDescartes is ERC20Detailed, ERC20, ERC20Mintable, ERC20Pausable, ERC20Burnable, Ownable,ERC1132 { /** * @dev Error messages for require statements */ string internal constant ALREADY_LOCKED = 'Tokens already locked'; string internal constant NOT_LOCKED = 'No tokens locked'; string internal constant AMOUNT_ZERO = 'Amount can not be 0'; string internal constant NOT_ENOUGH_TOKENS = 'Not enough tokens'; bool internal _mint_finish = false; //블럭상태 맵핑, 블럭이벤트 정의 mapping(address => bool) public blockedAccount; event BlockAccount(address target, bool state); event MintFinish(); constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) ERC20Detailed(name, symbol, decimals) public { _mint(owner(), totalSupply * 10 ** uint(decimals)); } //Mint finish function mintFinish () public onlyOwner { require(!_mint_finish, "ERC20: Already finished"); _mint_finish = true; emit MintFinish (); } //mint 메쏘드 재정의 function mint(address account, uint256 amount) public onlyMinter returns (bool) { require(!_mint_finish , "ERC20: Already finished"); _mint(account, amount); return true; } //계정 동결(사용불가상태로 만들기) // 파라미터 (블럭할주소,블럭상태) / 상태가 true일시 블럭함, 블럭취소시 상태를 false 호출하면 블럭해제 function blockAccount (address target, bool state) public onlyOwner { blockedAccount[target] = state; emit BlockAccount (target,state); } // _transfer 재정의 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"); //sender나 recipient가 블럭상태인지 아닌지 체크 require(!blockedAccount[sender], "Sender account has blocked"); require(!blockedAccount[recipient], "Recipient account has blocked"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address to be locked // 추가 */ function lock(bytes32 _reason, uint256 _amount, uint256 _time, address _of) public onlyOwner returns (bool) { uint256 validUntil = now.add(_time); //solhint-disable-line // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes require(_amount <= _balances[_of], NOT_ENOUGH_TOKENS); // 추가 require(tokensLocked(_of, _reason) == 0, ALREADY_LOCKED); require(_amount != 0, AMOUNT_ZERO); if (locked[_of][_reason].amount == 0){ lockReason[_of].push(_reason); } // transfer(address(this), _amount); // 수정 _balances[address(this)] = _balances[address(this)].add(_amount); _balances[_of] = _balances[_of].sub(_amount); locked[_of][_reason] = lockToken(_amount, validUntil, false); // 수정 emit Transfer(_of, address(this), _amount); emit Locked(_of, _reason, _amount, validUntil); return true; } /** * @dev Transfers and Locks a specified amount of tokens, * for a specified reason and time * @param _to adress to which tokens are to be transfered * @param _reason The reason to lock tokens * @param _amount Number of tokens to be transfered and locked * @param _time Lock time in seconds */ function transferWithLock(address _to, bytes32 _reason, uint256 _amount, uint256 _time) public onlyOwner returns (bool) { uint256 validUntil = now.add(_time ); //solhint-disable-line require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED); require(_amount != 0, AMOUNT_ZERO); if (locked[_to][_reason].amount == 0){ lockReason[_to].push(_reason); } transfer(address(this), _amount); locked[_to][_reason] = lockToken(_amount, validUntil, false); emit Locked(_to, _reason, _amount, validUntil); return true; } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public onlyOwner view returns (uint256 amount) { if (!locked[_of][_reason].claimed){ amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public onlyOwner view returns (uint256 amount) { if (locked[_of][_reason].validity > _time){ amount = locked[_of][_reason].amount; } } /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public onlyOwner view returns (uint256 amount) { amount = balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(tokensLocked(_of, lockReason[_of][i])); } } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public onlyOwner returns (bool) { require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED); locked[msg.sender][_reason].validity = locked[msg.sender][_reason].validity.add(_time); emit Locked(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity); return true; } /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public onlyOwner returns (bool) { require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED); transfer(address(this), _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); emit Locked(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity); return true; } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public onlyOwner view returns (uint256 amount) { //주석처리함 // if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) //solhint-disable-line amount = locked[_of][_reason].amount; } /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public onlyOwner returns (uint256 unlockableTokens) { uint256 lockedTokens; for (uint256 i = 0; i < lockReason[_of].length; i++) { lockedTokens = tokensUnlockable(_of, lockReason[_of][i]); if (lockedTokens > 0) { unlockableTokens = unlockableTokens.add(lockedTokens); locked[_of][lockReason[_of][i]].claimed = true; emit Unlocked(_of, lockReason[_of][i], lockedTokens); } } if (unlockableTokens > 0) { this.transfer(_of, unlockableTokens); } } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public onlyOwner view returns (uint256 unlockableTokens){ for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(tokensUnlockable(_of, lockReason[_of][i])); } } }
mapping (address => uint256) private _balances;
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } 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); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } 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); } function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } }
11,976,616
[ 1, 6770, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 353, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 2713, 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, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 12, 3576, 18, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 12, 3576, 18, 15330, 16, 17571, 264, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.9.0; import "./libraries/math/WadRayMath.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "hardhat/console.sol"; contract UsdPlusToken is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, AccessControlUpgradeable, UUPSUpgradeable { using WadRayMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; // --- ERC20 fields mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; // --- fields bytes32 public constant EXCHANGER = keccak256("EXCHANGER"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); uint256 private _totalMint; uint256 private _totalBurn; uint256 public liquidityIndexChangeTime; uint256 public liquidityIndex; uint256 public liquidityIndexDenominator; EnumerableSet.AddressSet _owners; // --- events event ExchangerUpdated(address exchanger); event LiquidityIndexUpdated(uint256 changeTime, uint256 liquidityIndex); // --- modifiers modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Restricted to admins"); _; } modifier onlyExchanger() { require(hasRole(EXCHANGER, msg.sender), "Caller is not the EXCHANGER"); _; } // --- setters function setExchanger(address _exchanger) external onlyAdmin { grantRole(EXCHANGER, _exchanger); emit ExchangerUpdated(_exchanger); } function setLiquidityIndex(uint256 _liquidityIndex) external onlyExchanger { require(_liquidityIndex > 0, "Zero liquidity index not allowed"); liquidityIndex = _liquidityIndex; liquidityIndexChangeTime = block.timestamp; emit LiquidityIndexUpdated(liquidityIndexChangeTime, liquidityIndex); } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __Context_init_unchained(); _name = "USD+"; _symbol = "USD+"; __AccessControl_init(); __UUPSUpgradeable_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(UPGRADER_ROLE, msg.sender); liquidityIndex = 10 ** 27; // as Ray liquidityIndexDenominator = 10 ** 27; // Ray } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER_ROLE) override {} // --- logic function mint(address _sender, uint256 _amount) external onlyExchanger { // up to ray uint256 mintAmount = _amount.wadToRay(); mintAmount = mintAmount.rayDiv(liquidityIndex); _mint(_sender, mintAmount); _totalMint += mintAmount; emit Transfer(address(0), _sender, _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 { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; _afterTokenTransfer(address(0), account, amount); } function burn(address _sender, uint256 _amount) external onlyExchanger { // up to ray uint256 burnAmount = _amount.wadToRay(); burnAmount = burnAmount.rayDiv(liquidityIndex); _burn(_sender, burnAmount); _totalBurn += burnAmount; emit Transfer(_sender, address(0), _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"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; _afterTokenTransfer(account, address(0), amount); } /** * @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 { 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; _afterTokenTransfer(sender, recipient, amount); } /** * @dev See {IERC20-transfer}. */ function transfer(address recipient, uint256 amount) public override returns (bool) { // up to ray uint256 transferAmount = amount.wadToRay(); transferAmount = transferAmount.rayDiv(liquidityIndex); _transfer(_msgSender(), recipient, transferAmount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { uint256 allowanceRay = _allowance(owner, spender).rayMul(liquidityIndex); // ray -> wad return allowanceRay.rayToWad(); } /** * @dev See {IERC20-allowance}. */ function _allowance(address owner, address spender) internal view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. */ function approve(address spender, uint256 amount) external override returns (bool){ // up to ray uint256 scaledAmount = amount.wadToRay(); scaledAmount = scaledAmount.rayDiv(liquidityIndex); _approve(_msgSender(), spender, scaledAmount); return true; } /** * @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); } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { // up to ray uint256 scaledAmount = amount.wadToRay(); scaledAmount = scaledAmount.rayDiv(liquidityIndex); _transfer(sender, recipient, scaledAmount); uint256 currentAllowance = _allowance(sender, _msgSender()); require(currentAllowance >= scaledAmount, "UsdPlusToken: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - scaledAmount); } emit Transfer(sender, recipient, amount); return true; } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override returns (uint256) { // stored balance is ray (27) uint256 balanceInMapping = _balanceOf(user); // ray -> ray uint256 balanceRay = balanceInMapping.rayMul(liquidityIndex); // ray -> wad return balanceRay.rayToWad(); } /** * @dev See {IERC20-balanceOf}. */ function _balanceOf(address account) internal view returns (uint256) { return _balances[account]; } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256) { return _balanceOf(user); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override returns (uint256) { // stored totalSupply is ray (27) uint256 currentSupply = _totalSupply; // ray -> ray uint256 currentSupplyRay = currentSupply.rayMul(liquidityIndex); // ray -> wad return currentSupplyRay.rayToWad(); } function totalMint() external view returns (uint256) { uint256 totalMintRay = _totalMint.rayMul(liquidityIndex); return totalMintRay.rayToWad(); } function totalBurn() external view returns (uint256) { uint256 totalBurnRay = _totalBurn.rayMul(liquidityIndex); return totalBurnRay.rayToWad(); } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Returns the scaled total supply of the variable debt token * @return the scaled total supply **/ function scaledTotalSupply() public view returns (uint256) { return _totalSupply; } function ownerLength() external view returns (uint256) { return _owners.length(); } function ownerAt(uint256 index) external view returns (address) { return _owners.at(index); } function ownerBalanceAt(uint256 index) external view returns (uint256) { return balanceOf(_owners.at(index)); } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 pure override returns (uint8) { return 6; } /** * @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 { } function _afterTokenTransfer( address from, address to, uint256 amount ) internal { if (from == address(0)) { // mint _owners.add(to); } else if (to == address(0)) { // burn if (balanceOf(from) == 0) { _owners.remove(from); } } else { // transfer if (balanceOf(from) == 0) { _owners.remove(from); } _owners.add(to); } } uint256[50] private __gap; }
* @dev Returns the scaled total supply of the variable debt token @return the scaled total supply/
function scaledTotalSupply() public view returns (uint256) { return _totalSupply; }
15,853,207
[ 1, 1356, 326, 12304, 2078, 14467, 434, 326, 2190, 18202, 88, 1147, 327, 326, 12304, 2078, 14467, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12304, 5269, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-08-29 */ // SPDX-License-Identifier: unlicensed pragma solidity 0.8.4; // ---------------------------------------------------------------------------- // 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // assisted token transfers // ---------------------------------------------------------------------------- contract CancerToken is ERC20Interface, SafeMath { string public constant symbol = "CANC"; string public constant name = "Cancer Token"; uint8 public constant decimals = 8; uint public constant _totalSupply = 2100000000000000; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() { balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to receiver account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address receiver, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(msg.sender, receiver, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.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 override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from sender account to receiver account // // The calling account must already have sufficient tokens approve(...)-d // for spending from sender 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 sender, address receiver, uint tokens) public override returns (bool success) { balances[sender] = safeSub(balances[sender], tokens); allowed[sender][msg.sender] = safeSub(allowed[sender][msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(sender, receiver, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract CancerToken is ERC20Interface, SafeMath { string public constant symbol = "CANC"; string public constant name = "Cancer Token"; uint8 public constant decimals = 8; uint public constant _totalSupply = 2100000000000000; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() { balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } function transfer(address receiver, uint tokens) public override returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(msg.sender, receiver, tokens); return true; } function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address sender, address receiver, uint tokens) public override returns (bool success) { balances[sender] = safeSub(balances[sender], tokens); allowed[sender][msg.sender] = safeSub(allowed[sender][msg.sender], tokens); balances[receiver] = safeAdd(balances[receiver], tokens); emit Transfer(sender, receiver, tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } }
15,458,856
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 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, 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, 16351, 4480, 2750, 1345, 353, 4232, 39, 3462, 1358, 16, 14060, 10477, 288, 203, 565, 533, 1071, 5381, 3273, 273, 315, 39, 1258, 39, 14432, 203, 565, 533, 1071, 5381, 225, 508, 273, 315, 2568, 2750, 3155, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 1725, 31, 203, 565, 2254, 1071, 5381, 389, 4963, 3088, 1283, 273, 9035, 12648, 9449, 31, 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, 565, 3885, 1435, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 3849, 1476, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 565, 445, 7412, 12, 2867, 5971, 16, 2254, 2430, 13, 1071, 3849, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 4183, 1676, 12, 70, 26488, 63, 3576, 18, 15330, 6487, 2430, 1769, 203, 3639, 324, 26488, 63, 24454, 65, 273, 4183, 986, 12, 70, 26488, 63, 24454, 6487, 2430, 1769, 203, 3639, 2 ]
pragma solidity ^0.5.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. * * _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"); } } /** * @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"); } } } /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } library ERC20WithFees { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Calls transferFrom on the token, returning the value transferred /// after fees. function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) { uint256 balancesBefore = token.balanceOf(to); token.safeTransferFrom(from, to, value); uint256 balancesAfter = token.balanceOf(to); return Math.min(value, balancesAfter.sub(balancesBefore)); } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is 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, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } 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) { // Note: The deployed version has no revert reason /* solium-disable-next-line error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } /** * @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 is Ownable { address public pendingOwner; modifier onlyPendingOwner() { require(_msgSender() == pendingOwner, "Claimable: caller is not the pending owner"); _; } function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } /** * @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), "LinkedList: already in list"); require(isInList(self, target) || target == NULL, "LinkedList: 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), "LinkedList: already in list"); require(isInList(self, target) || target == NULL, "LinkedList: 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), "LinkedList: 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), "LinkedList: not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].previous; } } contract CanReclaimTokens is Ownable { mapping(address => bool) private recoverableTokensBlacklist; function blacklistRecoverableToken(address _token) public { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require(!recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable"); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).transfer(msg.sender, ERC20(_token).balanceOf(address(this))); } } } /// @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, CanReclaimTokens { 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; blacklistRecoverableToken(address(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), "DarknodeRegistryStore: 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, "DarknodeRegistryStore: bond not decreased"); darknodeRegistry[darknodeID].bond = decreasedBond; require(ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: 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; } } interface IDarknodePaymentStore { } interface IDarknodePayment { function changeCycle() external returns (uint256); function store() external returns (IDarknodePaymentStore); } interface IDarknodeSlasher { } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Claimable, CanReclaimTokens { 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 blocktime; } 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; /// The Darknode Payment contract for changing cycle IDarknodePayment public darknodePayment; /// Darknode Slasher allows darknodes to vote on bond slashing. IDarknodeSlasher public slasher; IDarknodeSlasher public nextSlasher; /// @notice Emitted when a darknode is registered. /// @param _operator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address indexed _operator, address indexed _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _operator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered(address indexed _operator, address indexed _darknodeID); /// @notice Emitted when a refund has been made. /// @param _operator The owner of the darknode. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address indexed _operator, uint256 _amount); /// @notice Emitted when a darknode's bond is slashed. /// @param _operator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed(address indexed _operator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage); /// @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); event LogDarknodePaymentUpdated(IDarknodePayment _previousDarknodePayment, IDarknodePayment _nextDarknodePayment); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner"); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered"); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch"); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable"); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require(address(slasher) == msg.sender, "DarknodeRegistry: 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 _minimumEpochIntervalSeconds The minimum number of seconds between epochs. constructor( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocktime: block.timestamp }); 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), "DarknodeRegistry: bond transfer failed"); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, bond, _publicKey, currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _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.blocktime == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner(), "DarknodeRegistry: not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // 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)); } if (address(darknodePayment) != address(0x0)) { darknodePayment.changeCycle(); } // 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(DarknodeRegistry _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @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 { store.claimOwnership(); } /// @notice Allows the contract owner to update the address of the /// darknode payment contract. /// @param _darknodePayment The address of the Darknode Payment /// contract. function updateDarknodePayment(IDarknodePayment _darknodePayment) external onlyOwner { require(address(_darknodePayment) != address(0x0), "DarknodeRegistry: invalid Darknode Payment address"); IDarknodePayment previousDarknodePayment = darknodePayment; darknodePayment = _darknodePayment; emit LogDarknodePaymentUpdated(previousDarknodePayment, darknodePayment); } /// @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(IDarknodeSlasher _slasher) external onlyOwner { require(address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address"); nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash(address _guilty, address _challenger, uint256 _percentage) external onlySlasher { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 reward = penalty.div(2); if (reward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Distribute the remaining bond into the darknode payment reward pool require(address(darknodePayment) != address(0x0), "DarknodeRegistry: invalid payment address"); require(ren.transfer(address(darknodePayment.store()), reward), "DarknodeRegistry: reward transfer failed"); require(ren.transfer(_challenger, reward), "DarknodeRegistry: reward transfer failed"); } emit LogDarknodeSlashed(store.darknodeOwner(_guilty), _guilty, _challenger, _percentage); } /// @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), "DarknodeRegistry: 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.blocktime; } /// @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.blocktime; } /// @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.blocktime; } /// @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.blocktime; } /// @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.blocktime; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocktime; // 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.blocktime.add(minimumEpochInterval)); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(msg.sender, _darknodeID); } } /// @notice DarknodePaymentStore is responsible for tracking 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 SafeERC20 for ERC20; using ERC20WithFees for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Mapping of darknode -> token -> balance mapping(address => mapping(address => uint256)) public darknodeBalances; /// @notice Mapping of token -> lockedAmount mapping(address => uint256) public lockedBalances; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor( string memory _VERSION ) public { VERSION = _VERSION; } /// @notice Allow direct ETH payments to be made to the DarknodePaymentStore. function () external payable { } /// @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 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, "DarknodePaymentStore: invalid amount"); require(availableBalance(_token) >= _amount, "DarknodePaymentStore: 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, "DarknodePaymentStore: 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 Claimable { using SafeMath for uint256; using SafeERC20 for ERC20; using ERC20WithFees 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 changeCycle() // This defaults to the owner but should be changed to the DarknodeRegistry. address public cycleChanger; uint256 public currentCycle; uint256 public previousCycle; /// @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 staged payout percentage to the darknodes per cycle uint256 public nextCyclePayoutPercent; /// @notice The current cycle payout percentage to the darknodes uint256 public currentCyclePayoutPercent; /// @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 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 indexed _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 indexed _token); /// @notice Emitted when the payout percent changes /// @param _newPercent The new percent /// @param _oldPercent The old percent event LogPayoutPercentChanged(uint256 _newPercent, uint256 _oldPercent); /// @notice Emitted when the CycleChanger address changes /// @param _newCycleChanger The new CycleChanger /// @param _oldCycleChanger The old CycleChanger event LogCycleChangerChanged(address _newCycleChanger, address _oldCycleChanger); /// @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 Emitted when the DarknodeRegistry is updated. /// @param _previousDarknodeRegistry The address of the old registry. /// @param _nextDarknodeRegistry The address of the new registry. event LogDarknodeRegistryUpdated(DarknodeRegistry _previousDarknodeRegistry, DarknodeRegistry _nextDarknodeRegistry); /// @notice Restrict a function registered dark nodes to call a function. modifier onlyDarknode(address _darknode) { require(darknodeRegistry.isRegistered(_darknode), "DarknodePayment: darknode is not registered"); _; } /// @notice Restrict a function to have a valid percentage modifier validPercent(uint256 _percent) { require(_percent <= 100, "DarknodePayment: invalid percentage"); _; } /// @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 constructor( string memory _VERSION, DarknodeRegistry _darknodeRegistry, DarknodePaymentStore _darknodePaymentStore, uint256 _cyclePayoutPercent ) public validPercent(_cyclePayoutPercent) { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; store = _darknodePaymentStore; nextCyclePayoutPercent = _cyclePayoutPercent; // Default the cycleChanger to owner cycleChanger = msg.sender; // Start the current cycle (currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch(); currentCyclePayoutPercent = nextCyclePayoutPercent; } /// @notice Allows the contract owner to update the address of the /// darknode registry contract. /// @param _darknodeRegistry The address of the Darknode Registry /// contract. function updateDarknodeRegistry(DarknodeRegistry _darknodeRegistry) external onlyOwner { require(address(_darknodeRegistry) != address(0x0), "DarknodePayment: invalid Darknode Registry address"); DarknodeRegistry previousDarknodeRegistry = darknodeRegistry; darknodeRegistry = _darknodeRegistry; emit LogDarknodeRegistryUpdated(previousDarknodeRegistry, darknodeRegistry); } /// @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), "DarknodePayment: invalid darknode owner"); uint256 amount = store.darknodeBalances(_darknode, _token); require(amount > 0, "DarknodePayment: 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 { address(store).transfer(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) { uint256 total = store.availableBalance(_token).sub(unclaimedRewards[_token]); return total.div(100).mul(currentCyclePayoutPercent); } 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(msg.sender == cycleChanger, "DarknodePayment: not cycle changer"); // 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, cycleStartTime) = darknodeRegistry.currentEpoch(); currentCyclePayoutPercent = nextCyclePayoutPercent; // Update the list of registeredTokens _updateTokenList(); 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, "DarknodePayment: mismatched deposit value"); receivedValue = msg.value; address(store).transfer(msg.value); } else { require(msg.value == 0, "DarknodePayment: 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 Forwards any tokens that have been sent to the DarknodePayment contract /// probably by mistake, to the DarknodePaymentStore. /// /// @param _token The token address function forward(address _token) external { if (_token == ETHEREUM) { // Its unlikely that ETH will need to be forwarded, but it is // possible. For example - if ETH had already been sent to the // contract's address before it was deployed, or if funds are sent // to it as part of a contract's self-destruct. address(store).transfer(address(this).balance); } else { ERC20(_token).safeTransfer(address(store), ERC20(_token).balanceOf(address(this))); } } /// @notice Claims the rewards allocated to the darknode last epoch. /// @param _darknode The address of the darknode to claim function claim(address _darknode) external onlyDarknode(_darknode) { require(darknodeRegistry.isRegisteredInPreviousEpoch(_darknode), "DarknodePayment: cannot claim for this epoch"); // Claim share of rewards allocated for last cycle _claimDarknodeReward(_darknode); emit LogDarknodeClaim(_darknode, previousCycle); } /// @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, "DarknodePayment: token already registered"); require(!tokenPendingRegistration(_token), "DarknodePayment: token already pending registration"); pendingTokens.push(_token); } function tokenPendingRegistration(address _token) public view returns (bool) { uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { if (pendingTokens[i] == _token) { return true; } } return false; } /// @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, "DarknodePayment: token not registered"); _deregisterToken(_token); } /// @notice Updates the CycleChanger contract address. /// /// @param _addr The new CycleChanger contract address. function updateCycleChanger(address _addr) external onlyOwner { require(_addr != address(0), "DarknodePayment: invalid contract address"); emit LogCycleChangerChanged(_addr, cycleChanger); cycleChanger = _addr; } /// @notice Updates payout percentage /// /// @param _percent The percentage of payout for darknodes. function updatePayoutPercentage(uint256 _percent) external onlyOwner validPercent(_percent) { uint256 oldPayoutPercent = nextCyclePayoutPercent; nextCyclePayoutPercent = _percent; emit LogPayoutPercentChanged(nextCyclePayoutPercent, oldPayoutPercent); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodePaymentStore. /// /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodePayment _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @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 { 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], "DarknodePayment: 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 { uint256 shareCount = darknodeRegistry.numDarknodesPreviousEpoch(); if (shareCount == 0) { unclaimedRewards[_token] = 0; previousCycleRewardShare[_token] = 0; } else { // Lock up the current balance for darknode reward allocation uint256 total = store.availableBalance(_token); unclaimedRewards[_token] = total.div(100).mul(currentCyclePayoutPercent); 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 Emitted when a darknode's bond is slashed. @param _operator The owner of the darknode. @param _darknodeID The ID of the darknode that was slashed. @param _challenger The address of the account that submitted the challenge. @param _percentage The total percentage of bond slashed.
event LogDarknodeSlashed(address indexed _operator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage);
7,310,719
[ 1, 1514, 11541, 1347, 279, 23433, 2159, 1807, 8427, 353, 9026, 329, 18, 225, 389, 9497, 1021, 3410, 434, 326, 23433, 2159, 18, 225, 389, 25045, 2159, 734, 1021, 1599, 434, 326, 23433, 2159, 716, 1703, 9026, 329, 18, 225, 389, 343, 7862, 693, 1021, 1758, 434, 326, 2236, 716, 9638, 326, 12948, 18, 225, 389, 18687, 1021, 2078, 11622, 225, 434, 8427, 9026, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 871, 1827, 40, 1313, 2159, 11033, 329, 12, 2867, 8808, 389, 9497, 16, 1758, 8808, 389, 25045, 2159, 734, 16, 1758, 8808, 389, 343, 7862, 693, 16, 2254, 5034, 389, 18687, 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 ]
pragma solidity ^0.6.0; import "../governance/Operator.sol"; import "../interface/IUserRegistry.sol"; /** * @title UserRegistry * @dev UserRegistry contract * Configure and manage users_ * Extended may be used externaly to store data within a user context * * @author Cyril Lapinte - <[email protected]> * * Error messages * UR01: UserId is invalid * UR02: WalletOwner is already known * UR03: Users length does not match with addresses * UR04: WalletOwner is unknown * UR05: Sender is not the wallet owner * UR06: User is already suspended * UR07: User is not suspended */ contract UserRegistry is IUserRegistry, Operator { struct User { uint256 validUntilTime; bool suspended; mapping(uint256 => uint256) extended; } mapping(uint256 => User) public users_; mapping(address => uint256) public walletOwners_; uint256 public userCount_; /** * @dev contructor **/ constructor(address[] memory _addresses, uint256 _validUntilTime) public { for (uint256 i = 0; i < _addresses.length; i++) { _registerUserInternal(_addresses[i], _validUntilTime); } } /** * @dev number of user registered */ function userCount() override public view returns (uint256) { return userCount_; } /** * @dev the userId associated to the provided address */ function userId(address _address) override public view returns (uint256) { return walletOwners_[_address]; } /** * @dev the userId associated to the provided address if the user is valid */ function validUserId(address _address) override public view returns (uint256) { uint256 addressUserId = walletOwners_[_address]; if (_isValidInternal(users_[addressUserId])) { return addressUserId; } return 0; } /** * @dev returns the time at which user validity ends */ function validUntilTime(uint256 _userId) override public view returns (uint256) { return users_[_userId].validUntilTime; } /** * @dev is the user suspended */ function suspended(uint256 _userId) override public view returns (bool) { return users_[_userId].suspended; } /** * @dev access to extended user data */ function extended(uint256 _userId, uint256 _key) override public view returns (uint256) { return users_[_userId].extended[_key]; } /** * @dev validity of the current user */ function isAddressValid(address _address) override public view returns (bool) { return _isValidInternal(users_[walletOwners_[_address]]); } /** * @dev validity of the current user */ function isValid(uint256 _userId) override public view returns (bool) { return _isValidInternal(users_[_userId]); } /** * @dev register a user */ function registerUser(address _address, uint256 _validUntilTime) override public onlyOperator { _registerUserInternal(_address, _validUntilTime); } /** * @dev register many users_ */ function registerManyUsers(address[] memory _addresses, uint256 _validUntilTime) override public onlyOperator { for (uint256 i = 0; i < _addresses.length; i++) { _registerUserInternal(_addresses[i], _validUntilTime); } } /** * @dev attach an address with a user */ function attachAddress(uint256 _userId, address _address) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); require(walletOwners_[_address] == 0, "UR02"); walletOwners_[_address] = _userId; emit AddressAttached(_userId, _address); } /** * @dev attach many addresses to many users_ */ function attachManyAddresses(uint256[] memory _userIds, address[] memory _addresses) override public onlyOperator { require(_addresses.length == _userIds.length, "UR03"); for (uint256 i = 0; i < _addresses.length; i++) { attachAddress(_userIds[i], _addresses[i]); } } /** * @dev detach the association between an address and its user */ function detachAddress(address _address) override public onlyOperator { _detachAddressInternal(_address); } /** * @dev detach many addresses association between addresses and their respective users_ */ function detachManyAddresses(address[] memory _addresses) override public onlyOperator { for (uint256 i = 0; i < _addresses.length; i++) { _detachAddressInternal(_addresses[i]); } } /** * @dev detach the association between an address and its user */ function detachSelf() override public { _detachAddressInternal(msg.sender); } /** * @dev detach the association between an address and its user */ function detachSelfAddress(address _address) override public { uint256 senderUserId = walletOwners_[msg.sender]; require(walletOwners_[_address] == senderUserId, "UR05"); _detachAddressInternal(_address); } /** * @dev suspend a user */ function suspendUser(uint256 _userId) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); require(!users_[_userId].suspended, "UR06"); users_[_userId].suspended = true; } /** * @dev unsuspend a user */ function unsuspendUser(uint256 _userId) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); require(users_[_userId].suspended, "UR07"); users_[_userId].suspended = false; } /** * @dev suspend many users_ */ function suspendManyUsers(uint256[] memory _userIds) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { suspendUser(_userIds[i]); } } /** * @dev unsuspend many users_ */ function unsuspendManyUsers(uint256[] memory _userIds) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { unsuspendUser(_userIds[i]); } } /** * @dev update a user */ function updateUser( uint256 _userId, uint256 _validUntilTime, bool _suspended) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); users_[_userId].validUntilTime = _validUntilTime; users_[_userId].suspended = _suspended; } /** * @dev update many users_ */ function updateManyUsers( uint256[] memory _userIds, uint256 _validUntilTime, bool _suspended) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { updateUser(_userIds[i], _validUntilTime, _suspended); } } /** * @dev update user extended information */ function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); users_[_userId].extended[_key] = _value; } /** * @dev update many user extended informations */ function updateManyUsersExtended( uint256[] memory _userIds, uint256 _key, uint256 _value) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { updateUserExtended(_userIds[i], _key, _value); } } /** * @dev register a user */ function _registerUserInternal(address _address, uint256 _validUntilTime) internal { require(walletOwners_[_address] == 0, "UR03"); users_[++userCount_] = User(_validUntilTime, false); walletOwners_[_address] = userCount_; emit UserRegistered(userCount_); emit AddressAttached(userCount_, _address); } /** * @dev detach the association between an address and its user */ function _detachAddressInternal(address _address) internal { uint256 addressUserId = walletOwners_[_address]; require(addressUserId != 0, "UR04"); emit AddressDetached(addressUserId, _address); delete walletOwners_[_address]; } /** * @dev validity of the current user */ function _isValidInternal(User storage user) internal view returns (bool) { // solhint-disable-next-line not-rely-on-time return !user.suspended && user.validUntilTime > now; } }
* @dev is the user suspended/
function suspended(uint256 _userId) override public view returns (bool) { return users_[_userId].suspended; }
12,676,353
[ 1, 291, 326, 729, 21850, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 21850, 12, 11890, 5034, 389, 18991, 13, 3849, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 3677, 67, 63, 67, 18991, 8009, 87, 22942, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/stores/DataStore.sol
@param key The key for the record
function getUint(string calldata key) external view returns (uint256) { return uintValues[getHash(key)]; }
11,525,504
[ 1, 856, 1021, 498, 364, 326, 1409, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 5487, 12, 1080, 745, 892, 498, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2254, 1972, 63, 588, 2310, 12, 856, 13, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // File: contracts\zeppelin-solidity\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts\zeppelin-solidity\token\ERC20\ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts\zeppelin-solidity\lifecycle\TokenDestructible.sol /** * @title TokenDestructible: * @author Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4230272f212d0270">[email&#160;protected]</a>π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { function TokenDestructible() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } // File: contracts\zeppelin-solidity\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts\zeppelin-solidity\token\ERC20\BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts\zeppelin-solidity\token\ERC20\BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;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); } } // File: contracts\zeppelin-solidity\token\ERC20\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\zeppelin-solidity\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts\zeppelin-solidity\token\ERC20\MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint 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; } } // File: contracts\DemeterToken.sol /** * @title Demeter Token. * @dev Specific Demeter token. */ contract DemeterToken is TokenDestructible, BurnableToken, MintableToken { string public name = "Demeter.life"; string public symbol = "DME"; uint256 public decimals = 18; /** * @dev transfer the same amount of tokens to up to 100 specified addresses. * If the sender runs out of balance then the entire transaction fails. * @param _to The addresses to transfer to. * @param _value The amount to be transferred to each address. */ function airdrop(address[] _to, uint256 _value) public { require(_to.length <= 100); require(balanceOf(msg.sender) >= _value.mul(_to.length)); for (uint i = 0; i < _to.length; i++) { if (!transfer(_to[i], _value)) { revert(); } } } }
* @dev transfer the same amount of tokens to up to 100 specified addresses. If the sender runs out of balance then the entire transaction fails. @param _to The addresses to transfer to. @param _value The amount to be transferred to each address./
{ require(_to.length <= 100); require(balanceOf(msg.sender) >= _value.mul(_to.length)); for (uint i = 0; i < _to.length; i++) { if (!transfer(_to[i], _value)) { revert(); } } }
15,291,595
[ 1, 13866, 326, 1967, 3844, 434, 2430, 358, 731, 358, 2130, 1269, 6138, 18, 971, 326, 5793, 7597, 596, 434, 11013, 1508, 326, 7278, 2492, 6684, 18, 225, 389, 869, 1021, 6138, 358, 7412, 358, 18, 225, 389, 1132, 1021, 3844, 358, 506, 906, 4193, 358, 1517, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 288, 203, 565, 2583, 24899, 869, 18, 2469, 1648, 2130, 1769, 203, 565, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 389, 1132, 18, 16411, 24899, 869, 18, 2469, 10019, 203, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 869, 18, 2469, 31, 277, 27245, 203, 565, 288, 203, 1377, 309, 16051, 13866, 24899, 869, 63, 77, 6487, 389, 1132, 3719, 203, 1377, 288, 203, 3639, 15226, 5621, 203, 1377, 289, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title 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; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title 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); function mint(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); } /** * @dev Multiownable smart contract * which allows to many ETH wallets to manage main smart contract. */ contract Multiownable { // VARIABLES uint256 internal _ownersGeneration; uint256 internal _howManyOwnersDecide; address[] internal _owners; bytes32[] internal _allOperations; address internal _insideCallSender; uint256 internal _insideCallCount; // Reverse lookup tables for owners and allOperations mapping(address => uint256) public ownersIndices; // Starts from 1 mapping(bytes32 => uint256) public allOperationsIndicies; // Owners voting mask per operations mapping(bytes32 => uint256) public votesMaskByOperation; mapping(bytes32 => uint256) public votesCountByOperation; // EVENTS event OwnershipTransferred(address[] previousOwners, uint256 howManyOwnersDecide, address[] newOwners, uint256 newHowManyOwnersDecide); event OperationCreated(bytes32 operation, uint256 howMany, uint256 ownersCount, address proposer); event OperationUpvoted(bytes32 operation, uint256 votes, uint256 howMany, uint256 ownersCount, address upvoter); event OperationPerformed(bytes32 operation, uint256 howMany, uint256 ownersCount, address performer); event OperationDownvoted(bytes32 operation, uint256 votes, uint256 ownersCount, address downvoter); event OperationCancelled(bytes32 operation, address lastCanceller); // ACCESSORS function isOwner(address wallet) external view returns (bool) { return ownersIndices[wallet] > 0; } function ownersCount() external view returns (uint256) { return _owners.length; } function allOperationsCount() external view returns (uint256) { return _allOperations.length; } // MODIFIERS /** * @dev Allows to perform method by any of the owners */ modifier onlyAnyOwner { if (checkHowManyOwners(1)) { bool update = (_insideCallSender == address(0)); if (update) { _insideCallSender = msg.sender; _insideCallCount = 1; } _; if (update) { _insideCallSender = address(0); _insideCallCount = 0; } } } /** * @dev Allows to perform method only after many owners call it with the same arguments */ modifier onlyManyOwners { if (checkHowManyOwners(_howManyOwnersDecide)) { bool update = (_insideCallSender == address(0)); if (update) { _insideCallSender = msg.sender; _insideCallCount = _howManyOwnersDecide; } _; if (update) { _insideCallSender = address(0); _insideCallCount = 0; } } } /** * @dev Allows to perform method only after all owners call it with the same arguments */ modifier onlyAllOwners { if (checkHowManyOwners(_owners.length)) { bool update = (_insideCallSender == address(0)); if (update) { _insideCallSender = msg.sender; _insideCallCount = _owners.length; } _; if (update) { _insideCallSender = address(0); _insideCallCount = 0; } } } /** * @dev Allows to perform method only after some owners call it with the same arguments */ modifier onlySomeOwners(uint256 howMany) { require(howMany > 0, "onlySomeOwners: howMany argument is zero"); require(howMany <= _owners.length, "onlySomeOwners: howMany argument exceeds the number of owners"); if (checkHowManyOwners(howMany)) { bool update = (_insideCallSender == address(0)); if (update) { _insideCallSender = msg.sender; _insideCallCount = howMany; } _; if (update) { _insideCallSender = address(0); _insideCallCount = 0; } } } // CONSTRUCTOR constructor() public { _owners.push(msg.sender); ownersIndices[msg.sender] = 1; _howManyOwnersDecide = 1; } // INTERNAL METHODS /** * @dev onlyManyOwners modifier helper */ function checkHowManyOwners(uint256 howMany) internal returns (bool) { if (_insideCallSender == msg.sender) { require(howMany <= _insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners"); return true; } uint256 ownerIndex = ownersIndices[msg.sender] - 1; require(ownerIndex < _owners.length, "checkHowManyOwners: msg.sender is not an owner"); bytes32 operation = keccak256(abi.encodePacked(msg.data, _ownersGeneration)); require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation"); votesMaskByOperation[operation] |= (2 ** ownerIndex); uint256 operationVotesCount = votesCountByOperation[operation] + 1; votesCountByOperation[operation] = operationVotesCount; if (operationVotesCount == 1) { allOperationsIndicies[operation] = _allOperations.length; _allOperations.push(operation); emit OperationCreated(operation, howMany, _owners.length, msg.sender); } emit OperationUpvoted(operation, operationVotesCount, howMany, _owners.length, msg.sender); // If enough owners confirmed the same operation if (votesCountByOperation[operation] == howMany) { deleteOperation(operation); emit OperationPerformed(operation, howMany, _owners.length, msg.sender); return true; } return false; } /** * @dev Used to delete cancelled or performed operation * @param operation defines which operation to delete */ function deleteOperation(bytes32 operation) internal { uint256 index = allOperationsIndicies[operation]; if (index < _allOperations.length - 1) { // Not last _allOperations[index] = _allOperations[_allOperations.length - 1]; allOperationsIndicies[_allOperations[index]] = index; } _allOperations.length--; delete votesMaskByOperation[operation]; delete votesCountByOperation[operation]; delete allOperationsIndicies[operation]; } // PUBLIC METHODS /** * @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations * @param operation defines which operation to delete */ function cancelPending(bytes32 operation) external onlyAnyOwner { uint256 ownerIndex = ownersIndices[msg.sender] - 1; require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user"); votesMaskByOperation[operation] &= ~(2 ** ownerIndex); uint256 operationVotesCount = votesCountByOperation[operation] - 1; votesCountByOperation[operation] = operationVotesCount; emit OperationDownvoted(operation, operationVotesCount, _owners.length, msg.sender); if (operationVotesCount == 0) { deleteOperation(operation); emit OperationCancelled(operation, msg.sender); } } /** * @dev Allows owners to change ownership * @param newOwners defines array of addresses of new owners */ function transferOwnership(address[] calldata newOwners) external { transferOwnershipWithHowMany(newOwners, newOwners.length); } /** * @dev Allows owners to change ownership * @param newOwners defines array of addresses of new owners * @param newHowManyOwnersDecide defines how many owners can decide */ function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners { require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty"); require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256"); require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0"); require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners"); // Reset owners reverse lookup table for (uint256 j = 0; j < _owners.length; j++) { delete ownersIndices[_owners[j]]; } for (uint256 i = 0; i < newOwners.length; i++) { require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero"); require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates"); ownersIndices[newOwners[i]] = i + 1; } emit OwnershipTransferred(_owners, _howManyOwnersDecide, newOwners, newHowManyOwnersDecide); _owners = newOwners; _howManyOwnersDecide = newHowManyOwnersDecide; _allOperations.length = 0; _ownersGeneration++; } // GETTERS function getOwnersGeneration() external view returns (uint256) { return _ownersGeneration; } function getHowManyOwnersDecide() external view returns (uint256) { return _howManyOwnersDecide; } function getInsideCallSender() external view returns (address) { return _insideCallSender; } function getInsideCallCount() external view returns (uint256) { return _insideCallCount; } function getOwners() external view returns(address [] memory) { return _owners; } function getAllOperations() external view returns (bytes32 [] memory) { return _allOperations; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is Multiownable { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(msg.sender), "WhitelistedRole: caller does not have the Whitelisted role"); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyManyOwners { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyManyOwners { _removeWhitelisted(account); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } /** * @title Staking smart contract */ contract Staking is WhitelistedRole { using SafeMath for uint256; using SafeERC20 for IERC20; // whitelisted users amount uint256 private _usersAmount; // timestamp when last time deposit was deposited tokens uint256 private _lastDepositDone; // only once per 30 days depositor can deposit tokens uint256 private constant _depositDelay = 30 days; // the address of depositor address private _depositor; // how much deposits depositor done uint256 private _depositsAmount; struct DepositData { uint256 tokens; uint256 usersLength; } // here we store the history of deposits amount per each delay mapping(uint256 => DepositData) private _depositedPerDelay; // here we store user address => last deposit amount for withdraw calculation // if user missed withdrawal of few months he can withdraw all tokens once mapping(address => uint256) private _userWithdraws; // interface of ERC20 Yazom IERC20 private _yazom; // events for watching event Deposited(uint256 amount); event Withdrawen(address indexed user, uint256 amount); // ----------------------------------------- // CONSTRUCTOR // ----------------------------------------- constructor (address depositor, IERC20 yazom) public { _depositor = depositor; _yazom = yazom; } // ----------------------------------------- // EXTERNAL // ----------------------------------------- function () external payable { // revert fallback methods revert(); } function deposit() external { require(msg.sender == _depositor, "deposit: only the depositor can deposit tokens"); require(block.timestamp >= _lastDepositDone.add(_depositDelay), "deposit: can not deposit now"); uint256 tokensAmount = _yazom.allowance(_depositor, address(this)); _yazom.safeTransferFrom(_depositor, address(this), tokensAmount); _lastDepositDone = block.timestamp; _depositedPerDelay[_depositsAmount] = DepositData(tokensAmount, _usersAmount); _depositsAmount += 1; emit Deposited(tokensAmount); } function withdrawn() external onlyWhitelisted { address user = msg.sender; uint256 userLastWithdrawal = _userWithdraws[user]; require(userLastWithdrawal < _depositsAmount, "withdrawn: this user already withdraw all available funds"); uint256 tokensAmount; for (uint256 i = userLastWithdrawal; i < _depositsAmount; i++) { uint256 tokensPerDelay = _depositedPerDelay[i].tokens.div(_depositedPerDelay[i].usersLength); tokensAmount = tokensPerDelay; } _userWithdraws[user] = _depositsAmount; _yazom.safeTransfer(user, tokensAmount); emit Withdrawen(user, tokensAmount); } // ----------------------------------------- // INTERNAL // ----------------------------------------- function _addWhitelisted(address account) internal { _usersAmount++; super._addWhitelisted(account); } function _removeWhitelisted(address account) internal { _usersAmount--; super._removeWhitelisted(account); } // ----------------------------------------- // GETTERS // ----------------------------------------- function getCurrentUsersAmount() external view returns (uint256) { return _usersAmount; } function getLastDepositDoneDate() external view returns (uint256) { return _lastDepositDone; } function getDepositDelay() external pure returns (uint256) { return _depositDelay; } function getDepositorAddress() external view returns (address) { return _depositor; } function getDepositsAmount() external view returns (uint256) { return _depositsAmount; } function getDepositData(uint256 depositId) external view returns (uint256 tokens, uint256 usersLength) { return ( _depositedPerDelay[depositId].tokens, _depositedPerDelay[depositId].usersLength ); } function getUserLastWithdraw(address user) external view returns (uint256) { return _userWithdraws[user]; } }
* @dev Allows owners to change ownership @param newOwners defines array of addresses of new owners @param newHowManyOwnersDecide defines how many owners can decide/ Reset owners reverse lookup table
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners { require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty"); require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256"); require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0"); require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners"); for (uint256 j = 0; j < _owners.length; j++) { delete ownersIndices[_owners[j]]; } for (uint256 i = 0; i < newOwners.length; i++) { require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero"); require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates"); ownersIndices[newOwners[i]] = i + 1; } emit OwnershipTransferred(_owners, _howManyOwnersDecide, newOwners, newHowManyOwnersDecide); _owners = newOwners; _howManyOwnersDecide = newHowManyOwnersDecide; _allOperations.length = 0; _ownersGeneration++; }
1,796,735
[ 1, 19132, 25937, 358, 2549, 23178, 225, 394, 5460, 414, 11164, 526, 434, 6138, 434, 394, 25937, 225, 394, 44, 543, 5594, 5460, 414, 1799, 831, 11164, 3661, 4906, 25937, 848, 16288, 19, 7151, 25937, 4219, 3689, 1014, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 5460, 12565, 1190, 44, 543, 5594, 12, 2867, 8526, 3778, 394, 5460, 414, 16, 2254, 5034, 394, 44, 543, 5594, 5460, 414, 1799, 831, 13, 1071, 1338, 5594, 5460, 414, 288, 203, 3639, 2583, 12, 2704, 5460, 414, 18, 2469, 405, 374, 16, 315, 13866, 5460, 12565, 1190, 44, 543, 5594, 30, 25937, 526, 353, 1008, 8863, 203, 3639, 2583, 12, 2704, 5460, 414, 18, 2469, 1648, 8303, 16, 315, 13866, 5460, 12565, 1190, 44, 543, 5594, 30, 25937, 1056, 353, 6802, 1508, 8303, 8863, 203, 3639, 2583, 12, 2704, 44, 543, 5594, 5460, 414, 1799, 831, 405, 374, 16, 315, 13866, 5460, 12565, 1190, 44, 543, 5594, 30, 394, 44, 543, 5594, 5460, 414, 1799, 831, 3959, 358, 374, 8863, 203, 3639, 2583, 12, 2704, 44, 543, 5594, 5460, 414, 1799, 831, 1648, 394, 5460, 414, 18, 2469, 16, 315, 13866, 5460, 12565, 1190, 44, 543, 5594, 30, 394, 44, 543, 5594, 5460, 414, 1799, 831, 14399, 326, 1300, 434, 25937, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 389, 995, 414, 18, 2469, 31, 525, 27245, 288, 203, 5411, 1430, 25937, 8776, 63, 67, 995, 414, 63, 78, 13563, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 394, 5460, 414, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 2704, 5460, 414, 63, 77, 65, 480, 1758, 12, 20, 3631, 315, 13866, 5460, 12565, 1190, 44, 543, 5594, 30, 25937, 526, 1914, 3634, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-06-10 */ pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); 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); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract DisputeManager is IDisputeManager, ICRVotingOwner, ControlledRecoverable { using SafeERC20 for IERC20; using SafeMath for uint256; using SafeMath64 for uint64; using PctHelpers for uint256; using Uint256Helpers for uint256; // Disputes-related error messages string private constant ERROR_SUBJECT_NOT_DISPUTE_SUBJECT = "DM_SUBJECT_NOT_DISPUTE_SUBJECT"; string private constant ERROR_EVIDENCE_PERIOD_IS_CLOSED = "DM_EVIDENCE_PERIOD_IS_CLOSED"; string private constant ERROR_TERM_OUTDATED = "DM_TERM_OUTDATED"; string private constant ERROR_DISPUTE_DOES_NOT_EXIST = "DM_DISPUTE_DOES_NOT_EXIST"; string private constant ERROR_INVALID_RULING_OPTIONS = "DM_INVALID_RULING_OPTIONS"; string private constant ERROR_DEPOSIT_FAILED = "DM_DEPOSIT_FAILED"; string private constant ERROR_BAD_MAX_DRAFT_BATCH_SIZE = "DM_BAD_MAX_DRAFT_BATCH_SIZE"; // Rounds-related error messages string private constant ERROR_ROUND_IS_FINAL = "DM_ROUND_IS_FINAL"; string private constant ERROR_ROUND_DOES_NOT_EXIST = "DM_ROUND_DOES_NOT_EXIST"; string private constant ERROR_INVALID_ADJUDICATION_STATE = "DM_INVALID_ADJUDICATION_STATE"; string private constant ERROR_ROUND_ALREADY_DRAFTED = "DM_ROUND_ALREADY_DRAFTED"; string private constant ERROR_DRAFT_TERM_NOT_REACHED = "DM_DRAFT_TERM_NOT_REACHED"; string private constant ERROR_VOTER_WEIGHT_ZERO = "DM_VOTER_WEIGHT_ZERO"; string private constant ERROR_ROUND_NOT_APPEALED = "DM_ROUND_NOT_APPEALED"; string private constant ERROR_INVALID_APPEAL_RULING = "DM_INVALID_APPEAL_RULING"; // Settlements-related error messages string private constant ERROR_PREV_ROUND_NOT_SETTLED = "DM_PREVIOUS_ROUND_NOT_SETTLED"; string private constant ERROR_ROUND_ALREADY_SETTLED = "DM_ROUND_ALREADY_SETTLED"; string private constant ERROR_ROUND_NOT_SETTLED = "DM_ROUND_PENALTIES_NOT_SETTLED"; string private constant ERROR_GUARDIAN_ALREADY_REWARDED = "DM_GUARDIAN_ALREADY_REWARDED"; string private constant ERROR_WONT_REWARD_NON_VOTER_GUARDIAN = "DM_WONT_REWARD_NON_VOTER_GUARD"; string private constant ERROR_WONT_REWARD_INCOHERENT_GUARDIAN = "DM_WONT_REWARD_INCOHERENT_GUARD"; string private constant ERROR_ROUND_APPEAL_ALREADY_SETTLED = "DM_APPEAL_ALREADY_SETTLED"; // Minimum possible rulings for a dispute uint8 internal constant MIN_RULING_OPTIONS = 2; // Maximum possible rulings for a dispute, equal to minimum limit uint8 internal constant MAX_RULING_OPTIONS = MIN_RULING_OPTIONS; // Precision factor used to improve rounding when computing weights for the final round uint256 internal constant FINAL_ROUND_WEIGHT_PRECISION = 1000; // Mask used to decode vote IDs uint256 internal constant VOTE_ID_MASK = 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; struct Dispute { IArbitrable subject; // Arbitrable associated to a dispute uint64 createTermId; // Term ID when the dispute was created uint8 possibleRulings; // Number of possible rulings guardians can vote for each dispute uint8 finalRuling; // Winning ruling of a dispute DisputeState state; // State of a dispute: pre-draft, adjudicating, or ruled AdjudicationRound[] rounds; // List of rounds for each dispute } struct AdjudicationRound { uint64 draftTermId; // Term from which the guardians of a round can be drafted uint64 guardiansNumber; // Number of guardians drafted for a round bool settledPenalties; // Whether or not penalties have been settled for a round uint256 guardianFees; // Total amount of fees to be distributed between the winning guardians of a round address[] guardians; // List of guardians drafted for a round mapping (address => GuardianState) guardiansStates; // List of states for each drafted guardian indexed by address uint64 delayedTerms; // Number of terms a round was delayed based on its requested draft term id uint64 selectedGuardians; // Number of guardians selected for a round, to allow drafts to be batched uint64 coherentGuardians; // Number of drafted guardians that voted in favor of the dispute final ruling uint64 settledGuardians; // Number of guardians whose rewards were already settled uint256 collectedTokens; // Total amount of tokens collected from losing guardians Appeal appeal; // Appeal-related information of a round } struct GuardianState { uint64 weight; // Weight computed for a guardian on a round bool rewarded; // Whether or not a drafted guardian was rewarded } struct Appeal { address maker; // Address of the appealer uint8 appealedRuling; // Ruling appealing in favor of address taker; // Address of the one confirming an appeal uint8 opposedRuling; // Ruling opposed to an appeal bool settled; // Whether or not an appeal has been settled } struct DraftParams { uint256 disputeId; // Identification number of the dispute to be drafted uint256 roundId; // Identification number of the round to be drafted uint64 termId; // Identification number of the current term of the Court bytes32 draftTermRandomness; // Randomness of the term in which the dispute was requested to be drafted DraftConfig config; // Draft config of the Court at the draft term } struct NextRoundDetails { uint64 startTerm; // Term ID from which the next round will start uint64 guardiansNumber; // Guardians number for the next round DisputeState newDisputeState; // New state for the dispute associated to the given round after the appeal IERC20 feeToken; // ERC20 token used for the next round fees uint256 totalFees; // Total amount of fees to be distributed between the winning guardians of the next round uint256 guardianFees; // Total amount of fees for a regular round at the given term uint256 appealDeposit; // Amount to be deposit of fees for a regular round at the given term uint256 confirmAppealDeposit; // Total amount of fees for a regular round at the given term } // Max guardians to be drafted in each batch. To prevent running out of gas. We allow to change it because max gas per tx can vary // As a reference, drafting 100 guardians from a small tree of 4 would cost ~2.4M. Drafting 500, ~7.75M. uint64 public maxGuardiansPerDraftBatch; // List of all the disputes created in the Court Dispute[] internal disputes; event DisputeStateChanged(uint256 indexed disputeId, DisputeState indexed state); event EvidenceSubmitted(uint256 indexed disputeId, address indexed submitter, bytes evidence); event EvidencePeriodClosed(uint256 indexed disputeId, uint64 indexed termId); event NewDispute(uint256 indexed disputeId, IArbitrable indexed subject, uint64 indexed draftTermId, bytes metadata); event GuardianDrafted(uint256 indexed disputeId, uint256 indexed roundId, address indexed guardian); event RulingAppealed(uint256 indexed disputeId, uint256 indexed roundId, uint8 ruling); event RulingAppealConfirmed(uint256 indexed disputeId, uint256 indexed roundId, uint64 indexed draftTermId); event RulingComputed(uint256 indexed disputeId, uint8 indexed ruling); event PenaltiesSettled(uint256 indexed disputeId, uint256 indexed roundId, uint256 collectedTokens); event RewardSettled(uint256 indexed disputeId, uint256 indexed roundId, address guardian, uint256 tokens, uint256 fees); event AppealDepositSettled(uint256 indexed disputeId, uint256 indexed roundId); event MaxGuardiansPerDraftBatchChanged(uint64 maxGuardiansPerDraftBatch); /** * @dev Constructor function * @param _controller Address of the controller * @param _maxGuardiansPerDraftBatch Max number of guardians to be drafted per batch * @param _skippedDisputes Number of disputes to be skipped */ constructor(Controller _controller, uint64 _maxGuardiansPerDraftBatch, uint256 _skippedDisputes) Controlled(_controller) public { _setMaxGuardiansPerDraftBatch(_maxGuardiansPerDraftBatch); _skipDisputes(_skippedDisputes); } /** * @notice Create a dispute over `_subject` with `_possibleRulings` possible rulings * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external onlyController returns (uint256) { uint64 termId = _ensureCurrentTerm(); require(_possibleRulings >= MIN_RULING_OPTIONS && _possibleRulings <= MAX_RULING_OPTIONS, ERROR_INVALID_RULING_OPTIONS); // Create the dispute uint256 disputeId = disputes.length++; Dispute storage dispute = disputes[disputeId]; dispute.subject = _subject; dispute.possibleRulings = _possibleRulings; dispute.createTermId = termId; Config memory config = _getConfigAt(termId); uint64 draftTermId = termId.add(config.disputes.evidenceTerms); emit NewDispute(disputeId, _subject, draftTermId, _metadata); // Create first adjudication round of the dispute uint64 guardiansNumber = config.disputes.firstRoundGuardiansNumber; (IERC20 feeToken, uint256 guardianFees, uint256 totalFees) = _getRegularRoundFees(config.fees, guardiansNumber); _createRound(disputeId, DisputeState.PreDraft, draftTermId, guardiansNumber, guardianFees); // Pay round fees and return dispute id _depositAmount(address(_subject), feeToken, totalFees); return disputeId; } /** * @notice Submit evidence for a dispute #`_disputeId` * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external onlyController { (Dispute storage dispute, ) = _getDisputeAndRound(_disputeId, 0); require(dispute.subject == _subject, ERROR_SUBJECT_NOT_DISPUTE_SUBJECT); emit EvidenceSubmitted(_disputeId, _submitter, _evidence); } /** * @notice Close the evidence period of dispute #`_disputeId` * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external onlyController { (Dispute storage dispute, AdjudicationRound storage round) = _getDisputeAndRound(_disputeId, 0); require(dispute.subject == _subject, ERROR_SUBJECT_NOT_DISPUTE_SUBJECT); // Check current term is within the evidence submission period uint64 termId = _ensureCurrentTerm(); uint64 newDraftTermId = termId.add(1); require(newDraftTermId < round.draftTermId, ERROR_EVIDENCE_PERIOD_IS_CLOSED); // Update the draft term of the first round to the next term round.draftTermId = newDraftTermId; emit EvidencePeriodClosed(_disputeId, termId); } /** * @notice Draft guardians for the next round of dispute #`_disputeId` * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external { // Drafts can only be computed when the Court is up-to-date. Note that forcing a term transition won't work since the term randomness // is always based on the next term which means it won't be available anyway. IClock clock = _clock(); uint64 requiredTransitions = _clock().getNeededTermTransitions(); require(uint256(requiredTransitions) == 0, ERROR_TERM_OUTDATED); uint64 currentTermId = _getLastEnsuredTermId(); // Ensure dispute has not been drafted yet Dispute storage dispute = _getDispute(_disputeId); require(dispute.state == DisputeState.PreDraft, ERROR_ROUND_ALREADY_DRAFTED); // Ensure draft term randomness can be computed for the current block number uint256 roundId = dispute.rounds.length - 1; AdjudicationRound storage round = dispute.rounds[roundId]; uint64 draftTermId = round.draftTermId; require(draftTermId <= currentTermId, ERROR_DRAFT_TERM_NOT_REACHED); bytes32 draftTermRandomness = clock.ensureCurrentTermRandomness(); // Draft guardians for the given dispute and reimburse fees DraftConfig memory config = _getDraftConfig(draftTermId); bool draftEnded = _draft(round, _buildDraftParams(_disputeId, roundId, currentTermId, draftTermRandomness, config)); // If the drafting is over, update its state if (draftEnded) { // No need for SafeMath: we ensured `currentTermId` is greater than or equal to `draftTermId` above round.delayedTerms = currentTermId - draftTermId; dispute.state = DisputeState.Adjudicating; emit DisputeStateChanged(_disputeId, DisputeState.Adjudicating); } } /** * @notice Appeal round #`_roundId` of dispute #`_disputeId` in favor of ruling `_ruling` * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external { // Ensure current term and check that the given round can be appealed. // Note that if there was a final appeal the adjudication state will be 'Ended'. (Dispute storage dispute, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); _ensureAdjudicationState(dispute, _roundId, AdjudicationState.Appealing, config.disputes); // Ensure that the ruling being appealed in favor of is valid and different from the current winning ruling ICRVoting voting = _voting(); uint256 voteId = _getVoteId(_disputeId, _roundId); uint8 roundWinningRuling = voting.getWinningOutcome(voteId); require(roundWinningRuling != _ruling && voting.isValidOutcome(voteId, _ruling), ERROR_INVALID_APPEAL_RULING); // Update round appeal state Appeal storage appeal = round.appeal; appeal.maker = msg.sender; appeal.appealedRuling = _ruling; emit RulingAppealed(_disputeId, _roundId, _ruling); // Pay appeal deposit NextRoundDetails memory nextRound = _getNextRoundDetails(round, _roundId, config); _depositAmount(msg.sender, nextRound.feeToken, nextRound.appealDeposit); } /** * @notice Confirm appeal for round #`_roundId` of dispute #`_disputeId` in favor of ruling `_ruling` * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external { // Ensure current term and check that the given round is appealed and can be confirmed. // Note that if there was a final appeal the adjudication state will be 'Ended'. (Dispute storage dispute, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); _ensureAdjudicationState(dispute, _roundId, AdjudicationState.ConfirmingAppeal, config.disputes); // Ensure that the ruling being confirmed in favor of is valid and different from the appealed ruling Appeal storage appeal = round.appeal; uint256 voteId = _getVoteId(_disputeId, _roundId); require(appeal.appealedRuling != _ruling && _voting().isValidOutcome(voteId, _ruling), ERROR_INVALID_APPEAL_RULING); // Create a new adjudication round for the dispute NextRoundDetails memory nextRound = _getNextRoundDetails(round, _roundId, config); DisputeState newDisputeState = nextRound.newDisputeState; uint256 newRoundId = _createRound(_disputeId, newDisputeState, nextRound.startTerm, nextRound.guardiansNumber, nextRound.guardianFees); // Update previous round appeal state appeal.taker = msg.sender; appeal.opposedRuling = _ruling; emit RulingAppealConfirmed(_disputeId, newRoundId, nextRound.startTerm); // Pay appeal confirm deposit _depositAmount(msg.sender, nextRound.feeToken, nextRound.confirmAppealDeposit); } /** * @notice Compute the final ruling for dispute #`_disputeId` * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling) { (Dispute storage dispute, Config memory config) = _getDisputeWithConfig(_disputeId); subject = dispute.subject; finalRuling = _ensureFinalRuling(dispute, _disputeId, config); if (dispute.state != DisputeState.Ruled) { dispute.state = DisputeState.Ruled; emit RulingComputed(_disputeId, finalRuling); } } /** * @notice Settle penalties for round #`_roundId` of dispute #`_disputeId` * @dev In case of a regular round, all the drafted guardians that didn't vote in favor of the final ruling of the given dispute will be slashed. * In case of a final round, guardians are slashed when voting, thus it is considered these rounds settled at once. Rewards have to be * manually claimed through `settleReward` which will return pre-slashed tokens for the winning guardians of a final round as well. * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call. It can be set to zero to slash all the losing guardians of the * given round. This argument is only used when settling regular rounds. */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external { // Enforce that rounds are settled in order to avoid one round without incentive to settle. Even if there is a settle fee // it may not be big enough and all guardians in the round could be slashed. (Dispute storage dispute, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); require(_roundId == 0 || dispute.rounds[_roundId - 1].settledPenalties, ERROR_PREV_ROUND_NOT_SETTLED); // Ensure given round has not been fully settled yet require(!round.settledPenalties, ERROR_ROUND_ALREADY_SETTLED); // Ensure the final ruling of the given dispute is already computed uint8 finalRuling = _ensureFinalRuling(dispute, _disputeId, config); // Set the number of guardians that voted in favor of the final ruling if we haven't started settling yet uint256 voteId = _getVoteId(_disputeId, _roundId); if (round.settledGuardians == 0) { // Note that we are safe to cast the tally of a ruling to uint64 since the highest value a ruling can have is equal to the guardians // number for regular rounds or to the total active balance of the registry for final rounds, and both are ensured to fit in uint64. ICRVoting voting = _voting(); round.coherentGuardians = uint64(voting.getOutcomeTally(voteId, finalRuling)); } ITreasury treasury = _treasury(); IERC20 feeToken = config.fees.token; if (_isRegularRound(_roundId, config)) { // For regular appeal rounds we compute the amount of locked tokens that needs to get burned in batches. // The callers of this function will get rewarded in this case. uint256 guardiansSettled = _settleRegularRoundPenalties(round, voteId, finalRuling, config.disputes.penaltyPct, _guardiansToSettle, config.minActiveBalance); treasury.assign(feeToken, msg.sender, config.fees.settleFee.mul(guardiansSettled)); } else { // For the final appeal round, there is no need to settle in batches since, to guarantee scalability, // all the tokens are collected from guardians when they vote, and those guardians who // voted in favor of the winning ruling can claim their collected tokens back along with their reward. // Note that the caller of this function is not being reimbursed. round.settledPenalties = true; } if (round.settledPenalties) { uint256 collectedTokens = round.collectedTokens; emit PenaltiesSettled(_disputeId, _roundId, collectedTokens); _burnCollectedTokensIfNecessary(dispute, round, _roundId, treasury, feeToken, collectedTokens); } } /** * @notice Claim reward for round #`_roundId` of dispute #`_disputeId` for guardian `_guardian` * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external { // Ensure dispute round penalties are settled first (Dispute storage dispute, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); require(round.settledPenalties, ERROR_ROUND_NOT_SETTLED); // Ensure given guardian was not rewarded yet and was drafted for the given round GuardianState storage guardianState = round.guardiansStates[_guardian]; require(!guardianState.rewarded, ERROR_GUARDIAN_ALREADY_REWARDED); require(uint256(guardianState.weight) > 0, ERROR_WONT_REWARD_NON_VOTER_GUARDIAN); guardianState.rewarded = true; // Check if the given guardian has voted in favor of the final ruling of the dispute in this round ICRVoting voting = _voting(); uint256 voteId = _getVoteId(_disputeId, _roundId); require(voting.hasVotedInFavorOf(voteId, dispute.finalRuling, _guardian), ERROR_WONT_REWARD_INCOHERENT_GUARDIAN); uint256 collectedTokens = round.collectedTokens; IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); // Distribute the collected tokens of the guardians that were slashed weighted by the winning guardians. Note that we are penalizing guardians // that refused intentionally their vote for the final round. uint256 rewardTokens; if (collectedTokens > 0) { // Note that the number of coherent guardians has to be greater than zero since we already ensured the guardian has voted in favor of the // final ruling, therefore there will be at least one coherent guardian and divisions below are safe. rewardTokens = _getRoundWeightedAmount(round, guardianState, collectedTokens); guardiansRegistry.assignTokens(_guardian, rewardTokens); } // Reward the winning guardian with fees // Note that the number of coherent guardians has to be greater than zero since we already ensured the guardian has voted in favor of the // final ruling, therefore there will be at least one coherent guardian and divisions below are safe. uint256 rewardFees = _getRoundWeightedAmount(round, guardianState, round.guardianFees); _treasury().assign(config.fees.token, _guardian, rewardFees); // Set the lock for final round if (!_isRegularRound(_roundId, config)) { // Round end term ID (as it's final there's no draft delay nor appeal) plus the lock period DisputesConfig memory disputesConfig = config.disputes; guardiansRegistry.lockWithdrawals( _guardian, round.draftTermId + disputesConfig.commitTerms + disputesConfig.revealTerms + disputesConfig.finalRoundLockTerms ); } emit RewardSettled(_disputeId, _roundId, _guardian, rewardTokens, rewardFees); } /** * @notice Settle appeal deposits for round #`_roundId` of dispute #`_disputeId` * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external { // Ensure dispute round penalties are settled first (Dispute storage dispute, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); require(round.settledPenalties, ERROR_ROUND_NOT_SETTLED); // Ensure given round was appealed and has not been settled yet Appeal storage appeal = round.appeal; require(_existsAppeal(appeal), ERROR_ROUND_NOT_APPEALED); require(!appeal.settled, ERROR_ROUND_APPEAL_ALREADY_SETTLED); appeal.settled = true; emit AppealDepositSettled(_disputeId, _roundId); // Load next round details NextRoundDetails memory nextRound = _getNextRoundDetails(round, _roundId, config); IERC20 feeToken = nextRound.feeToken; uint256 totalFees = nextRound.totalFees; uint256 appealDeposit = nextRound.appealDeposit; uint256 confirmAppealDeposit = nextRound.confirmAppealDeposit; // If the appeal wasn't confirmed, return the entire deposit to appeal maker ITreasury treasury = _treasury(); if (!_isAppealConfirmed(appeal)) { treasury.assign(feeToken, appeal.maker, appealDeposit); return; } // If the appeal was confirmed and there is a winner, we transfer the total deposit to that party. Otherwise, if the final ruling wasn't // selected by any of the appealing parties or no guardian voted in the in favor of the possible outcomes, we split it between both parties. // Note that we are safe to access the dispute final ruling, since we already ensured that round penalties were settled. uint8 finalRuling = dispute.finalRuling; uint256 totalDeposit = appealDeposit.add(confirmAppealDeposit); if (appeal.appealedRuling == finalRuling) { treasury.assign(feeToken, appeal.maker, totalDeposit.sub(totalFees)); } else if (appeal.opposedRuling == finalRuling) { treasury.assign(feeToken, appeal.taker, totalDeposit.sub(totalFees)); } else { uint256 feesRefund = totalFees / 2; treasury.assign(feeToken, appeal.maker, appealDeposit.sub(feesRefund)); treasury.assign(feeToken, appeal.taker, confirmAppealDeposit.sub(feesRefund)); } } /** * @notice Ensure votes can be committed for vote #`_voteId`, revert otherwise * @dev This function will ensure the current term of the Court and revert in case votes cannot still be committed * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external { (Dispute storage dispute, uint256 roundId, Config memory config) = _decodeVoteId(_voteId); // Ensure current term and check that votes can still be committed for the given round _ensureAdjudicationState(dispute, roundId, AdjudicationState.Committing, config.disputes); } /** * @notice Ensure `voter` can commit votes for vote #`_voteId`, revert otherwise * @dev This function will ensure the current term of the Court and revert in case the given voter is not allowed to commit votes * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external onlyActiveVoting { (Dispute storage dispute, uint256 roundId, Config memory config) = _decodeVoteId(_voteId); // Ensure current term and check that votes can still be committed for the given round _ensureAdjudicationState(dispute, roundId, AdjudicationState.Committing, config.disputes); uint64 weight = _computeGuardianWeight(dispute, roundId, _voter, config); require(weight > 0, ERROR_VOTER_WEIGHT_ZERO); } /** * @notice Ensure `voter` can reveal votes for vote #`_voteId`, revert otherwise * @dev This function will ensure the current term of the Court and revert in case votes cannot still be revealed * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested dispute's round */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64) { (Dispute storage dispute, uint256 roundId, Config memory config) = _decodeVoteId(_voteId); // Ensure current term and check that votes can still be revealed for the given round _ensureAdjudicationState(dispute, roundId, AdjudicationState.Revealing, config.disputes); AdjudicationRound storage round = dispute.rounds[roundId]; return _getGuardianWeight(round, _voter); } /** * @notice Sets the global configuration for the max number of guardians to be drafted per batch to `_maxGuardiansPerDraftBatch` * @param _maxGuardiansPerDraftBatch Max number of guardians to be drafted per batch */ function setMaxGuardiansPerDraftBatch(uint64 _maxGuardiansPerDraftBatch) external onlyConfigGovernor { _setMaxGuardiansPerDraftBatch(_maxGuardiansPerDraftBatch); } /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken IERC20 token used for the fees * @return totalFees Total amount of fees for a regular round at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 totalFees) { uint64 currentTermId = _getCurrentTermId(); Config memory config = _getConfigAt(currentTermId); (feeToken,, totalFees) = _getRegularRoundFees(config.fees, config.disputes.firstRoundGuardiansNumber); } /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns ( IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId ) { Dispute storage dispute = _getDispute(_disputeId); subject = dispute.subject; possibleRulings = dispute.possibleRulings; state = dispute.state; finalRuling = dispute.finalRuling; createTermId = dispute.createTermId; // If a dispute exists, it has at least one round lastRoundId = dispute.rounds.length - 1; } /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ) { (Dispute storage dispute, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); state = _adjudicationStateAt(dispute, _roundId, _getCurrentTermId(), config.disputes); draftTerm = round.draftTermId; delayedTerms = round.delayedTerms; guardiansNumber = round.guardiansNumber; selectedGuardians = round.selectedGuardians; guardianFees = round.guardianFees; settledPenalties = round.settledPenalties; coherentGuardians = round.coherentGuardians; collectedTokens = round.collectedTokens; } /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling) { (, AdjudicationRound storage round) = _getDisputeAndRound(_disputeId, _roundId); Appeal storage appeal = round.appeal; maker = appeal.maker; appealedRuling = appeal.appealedRuling; taker = appeal.taker; opposedRuling = appeal.opposedRuling; } /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ) { (, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); require(_isRegularRound(_roundId, config), ERROR_ROUND_IS_FINAL); NextRoundDetails memory nextRound = _getNextRoundDetails(round, _roundId, config); return ( nextRound.startTerm, nextRound.guardiansNumber, nextRound.newDisputeState, nextRound.feeToken, nextRound.totalFees, nextRound.guardianFees, nextRound.appealDeposit, nextRound.confirmAppealDeposit ); } /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded) { (, AdjudicationRound storage round, Config memory config) = _getDisputeAndRoundWithConfig(_disputeId, _roundId); if (_isRegularRound(_roundId, config)) { weight = _getGuardianWeight(round, _guardian); } else { IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); uint256 activeBalance = guardiansRegistry.activeBalanceOfAt(_guardian, round.draftTermId); weight = _getMinActiveBalanceMultiple(activeBalance, config.minActiveBalance); } rewarded = round.guardiansStates[_guardian].rewarded; } /** * @dev Internal function to create a new round for a given dispute * @param _disputeId Identification number of the dispute to create a new round for * @param _disputeState New state for the dispute to be changed * @param _draftTermId Term ID when the guardians for the new round will be drafted * @param _guardiansNumber Number of guardians to be drafted for the new round * @param _guardianFees Total amount of fees to be shared between the winning guardians of the new round * @return Identification number of the new dispute round */ function _createRound( uint256 _disputeId, DisputeState _disputeState, uint64 _draftTermId, uint64 _guardiansNumber, uint256 _guardianFees ) internal returns (uint256) { // Update dispute state Dispute storage dispute = disputes[_disputeId]; dispute.state = _disputeState; // Create new requested round uint256 roundId = dispute.rounds.length++; AdjudicationRound storage round = dispute.rounds[roundId]; round.draftTermId = _draftTermId; round.guardiansNumber = _guardiansNumber; round.guardianFees = _guardianFees; // Create new vote for the new round ICRVoting voting = _voting(); uint256 voteId = _getVoteId(_disputeId, roundId); voting.createVote(voteId, dispute.possibleRulings); return roundId; } /** * @dev Internal function to ensure the adjudication state of a certain dispute round. This function will make sure the court term is updated. * This function assumes the given round exists. * @param _dispute Dispute to be checked * @param _roundId Identification number of the dispute round to be checked * @param _state Expected adjudication state for the given dispute round * @param _config Config at the draft term ID of the given dispute */ function _ensureAdjudicationState(Dispute storage _dispute, uint256 _roundId, AdjudicationState _state, DisputesConfig memory _config) internal { uint64 termId = _ensureCurrentTerm(); AdjudicationState roundState = _adjudicationStateAt(_dispute, _roundId, termId, _config); require(roundState == _state, ERROR_INVALID_ADJUDICATION_STATE); } /** * @dev Internal function to ensure the final ruling of a dispute. It will compute it only if missing. * @param _dispute Dispute to ensure its final ruling * @param _disputeId Identification number of the dispute to ensure its final ruling * @param _config Config at the draft term ID of the given dispute * @return Number of the final ruling ensured for the given dispute */ function _ensureFinalRuling(Dispute storage _dispute, uint256 _disputeId, Config memory _config) internal returns (uint8) { // Check if there was a final ruling already cached if (uint256(_dispute.finalRuling) > 0) { return _dispute.finalRuling; } // Ensure current term and check that the last adjudication round has ended. // Note that there will always be at least one round. uint256 lastRoundId = _dispute.rounds.length - 1; _ensureAdjudicationState(_dispute, lastRoundId, AdjudicationState.Ended, _config.disputes); // If the last adjudication round was appealed but no-one confirmed it, the final ruling is the outcome the // appealer vouched for. Otherwise, fetch the winning outcome from the voting app of the last round. AdjudicationRound storage lastRound = _dispute.rounds[lastRoundId]; Appeal storage lastAppeal = lastRound.appeal; bool isRoundAppealedAndNotConfirmed = _existsAppeal(lastAppeal) && !_isAppealConfirmed(lastAppeal); uint8 finalRuling = isRoundAppealedAndNotConfirmed ? lastAppeal.appealedRuling : _voting().getWinningOutcome(_getVoteId(_disputeId, lastRoundId)); // Store the winning ruling as the final decision for the given dispute _dispute.finalRuling = finalRuling; return finalRuling; } /** * @dev Internal function to slash all the guardians drafted for a round that didn't vote in favor of the final ruling of a dispute. Note that * the slashing can be batched handling the maximum number of guardians to be slashed on each call. * @param _round Round to slash the non-winning guardians of * @param _voteId Identification number of the voting associated to the given round * @param _finalRuling Winning ruling of the dispute corresponding to the given round * @param _penaltyPct Per ten thousand of the minimum active balance of a guardian to be slashed * @param _guardiansToSettle Maximum number of guardians to be slashed in this call. It can be set to zero to slash all the losing guardians of the round. * @param _minActiveBalance Minimum amount of guardian tokens that can be activated * @return Number of guardians slashed for the given round */ function _settleRegularRoundPenalties( AdjudicationRound storage _round, uint256 _voteId, uint8 _finalRuling, uint16 _penaltyPct, uint256 _guardiansToSettle, uint256 _minActiveBalance ) internal returns (uint256) { uint64 termId = _ensureCurrentTerm(); // The batch starts where the previous one ended, stored in _round.settledGuardians uint256 roundSettledGuardians = _round.settledGuardians; // Compute the amount of guardians that are going to be settled in this batch, which is returned by the function for fees calculation // Initially we try to reach the end of the guardians array uint256 batchSettledGuardians = _round.guardians.length.sub(roundSettledGuardians); // If the requested amount of guardians is not zero and it is lower that the remaining number of guardians to be settled for the given round, // we cap the number of guardians that are going to be settled in this batch to the requested amount. If not, we know we have reached the // last batch and we are safe to mark round penalties as settled. if (_guardiansToSettle > 0 && batchSettledGuardians > _guardiansToSettle) { batchSettledGuardians = _guardiansToSettle; } else { _round.settledPenalties = true; } // Update the number of round settled guardians. _round.settledGuardians = uint64(roundSettledGuardians.add(batchSettledGuardians)); // Prepare the list of guardians and penalties to either be slashed or returned based on their votes for the given round IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); address[] memory guardians = new address[](batchSettledGuardians); uint256[] memory penalties = new uint256[](batchSettledGuardians); for (uint256 i = 0; i < batchSettledGuardians; i++) { address guardian = _round.guardians[roundSettledGuardians + i]; guardians[i] = guardian; penalties[i] = _minActiveBalance.pct(_penaltyPct).mul(_round.guardiansStates[guardian].weight); } // Check which of the guardians voted in favor of the final ruling of the dispute in this round. Ask the registry to slash or unlocked the // locked active tokens of each guardian depending on their vote, and finally store the total amount of slashed tokens. bool[] memory guardiansInFavor = _voting().getVotersInFavorOf(_voteId, _finalRuling, guardians); _round.collectedTokens = _round.collectedTokens.add(guardiansRegistry.slashOrUnlock(termId, guardians, penalties, guardiansInFavor)); return batchSettledGuardians; } /** * @dev Internal function to compute the guardian weight for a dispute's round * @param _dispute Dispute to calculate the guardian's weight of * @param _roundId ID of the dispute's round to calculate the guardian's weight of * @param _guardian Address of the guardian to calculate the weight of * @param _config Config at the draft term ID of the given dispute * @return Computed weight of the requested guardian for the final round of the given dispute */ function _computeGuardianWeight( Dispute storage _dispute, uint256 _roundId, address _guardian, Config memory _config ) internal returns (uint64) { AdjudicationRound storage round = _dispute.rounds[_roundId]; return _isRegularRound(_roundId, _config) ? _getGuardianWeight(round, _guardian) : _computeGuardianWeightForFinalRound(_config, round, _guardian); } /** * @dev Internal function to compute the guardian weight for the final round. Note that for a final round the weight of * each guardian is equal to the number of times the min active balance the guardian has. This function will try to * collect said amount from the active balance of a guardian, acting as a lock to allow them to vote. * @param _config Court config to calculate the guardian's weight * @param _round Dispute round to calculate the guardian's weight for * @param _guardian Address of the guardian to calculate the weight of * @return Weight of the requested guardian for the final round of the given dispute */ function _computeGuardianWeightForFinalRound(Config memory _config, AdjudicationRound storage _round, address _guardian) internal returns (uint64) { // Fetch active balance and multiples of the min active balance from the registry IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); uint256 activeBalance = guardiansRegistry.activeBalanceOfAt(_guardian, _round.draftTermId); uint64 weight = _getMinActiveBalanceMultiple(activeBalance, _config.minActiveBalance); // If the guardian weight for the last round is zero, return zero if (weight == 0) { return uint64(0); } // To guarantee scalability of the final round, since all guardians may vote, we try to collect the amount of // active tokens that needs to be locked for each guardian when they try to commit their vote. uint256 weightedPenalty = activeBalance.pct(_config.disputes.penaltyPct); // If it was not possible to collect the amount to be locked, return 0 to prevent guardian from voting if (!guardiansRegistry.collectTokens(_guardian, weightedPenalty, _getLastEnsuredTermId())) { return uint64(0); } // If it was possible to collect the amount of active tokens to be locked, update the final round state _round.guardiansStates[_guardian].weight = weight; _round.collectedTokens = _round.collectedTokens.add(weightedPenalty); return weight; } /** * @dev Sets the global configuration for the max number of guardians to be drafted per batch * @param _maxGuardiansPerDraftBatch Max number of guardians to be drafted per batch */ function _setMaxGuardiansPerDraftBatch(uint64 _maxGuardiansPerDraftBatch) internal { require(_maxGuardiansPerDraftBatch > 0, ERROR_BAD_MAX_DRAFT_BATCH_SIZE); maxGuardiansPerDraftBatch = _maxGuardiansPerDraftBatch; emit MaxGuardiansPerDraftBatchChanged(_maxGuardiansPerDraftBatch); } /** * @dev Internal function to execute a deposit of tokens from an account to the Court treasury contract * @param _from Address transferring the amount of tokens * @param _token ERC20 token to execute a transfer from * @param _amount Amount of tokens to be transferred from the address transferring the funds to the Court treasury */ function _depositAmount(address _from, IERC20 _token, uint256 _amount) internal { if (_amount > 0) { ITreasury treasury = _treasury(); // No need to verify _token to be a contract as it's permissioned as the fee token require(_token.safeTransferFrom(_from, address(treasury), _amount), ERROR_DEPOSIT_FAILED); } } /** * @dev Internal function to get the stored guardian weight for a round. Note that the weight of a guardian is: * - For a regular round: the number of times a guardian was picked for the round round. * - For a final round: the relative active stake of a guardian's state over the total active tokens, only set after the guardian has voted. * @param _round Dispute round to calculate the guardian's weight of * @param _guardian Address of the guardian to calculate the weight of * @return Weight of the requested guardian for the given round */ function _getGuardianWeight(AdjudicationRound storage _round, address _guardian) internal view returns (uint64) { return _round.guardiansStates[_guardian].weight; } /** * @dev Internal function to tell information related to the next round due to an appeal of a certain round given. This function assumes * given round can be appealed and that the given round ID corresponds to the given round pointer. * @param _round Round requesting the appeal details of * @param _roundId Identification number of the round requesting the appeal details of * @param _config Config at the draft term of the given dispute * @return Next round details */ function _getNextRoundDetails(AdjudicationRound storage _round, uint256 _roundId, Config memory _config) internal view returns (NextRoundDetails memory) { NextRoundDetails memory nextRound; DisputesConfig memory disputesConfig = _config.disputes; // Next round start term is current round end term uint64 delayedDraftTerm = _round.draftTermId.add(_round.delayedTerms); uint64 currentRoundAppealStartTerm = delayedDraftTerm.add(disputesConfig.commitTerms).add(disputesConfig.revealTerms); nextRound.startTerm = currentRoundAppealStartTerm.add(disputesConfig.appealTerms).add(disputesConfig.appealConfirmTerms); // Compute next round settings depending on if it will be the final round or not if (_roundId >= disputesConfig.maxRegularAppealRounds.sub(1)) { // If the next round is the final round, no draft is needed. nextRound.newDisputeState = DisputeState.Adjudicating; // The number of guardians will be the number of times the minimum stake is held in the registry, // multiplied by a precision factor to help with division rounding. // Total active balance is guaranteed to never be greater than `2^64 * minActiveBalance / FINAL_ROUND_WEIGHT_PRECISION`. // Thus, the guardians number for a final round will always fit in uint64. IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); uint256 totalActiveBalance = guardiansRegistry.totalActiveBalanceAt(nextRound.startTerm); uint64 guardiansNumber = _getMinActiveBalanceMultiple(totalActiveBalance, _config.minActiveBalance); nextRound.guardiansNumber = guardiansNumber; // Calculate fees for the final round using the appeal start term of the current round (nextRound.feeToken, nextRound.guardianFees, nextRound.totalFees) = _getFinalRoundFees(_config.fees, guardiansNumber); } else { // For a new regular rounds we need to draft guardians nextRound.newDisputeState = DisputeState.PreDraft; // The number of guardians will be the number of guardians of the current round multiplied by an appeal factor nextRound.guardiansNumber = _getNextRegularRoundGuardiansNumber(_round, disputesConfig); // Calculate fees for the next regular round using the appeal start term of the current round (nextRound.feeToken, nextRound.guardianFees, nextRound.totalFees) = _getRegularRoundFees(_config.fees, nextRound.guardiansNumber); } // Calculate appeal collateral nextRound.appealDeposit = nextRound.totalFees.pct256(disputesConfig.appealCollateralFactor); nextRound.confirmAppealDeposit = nextRound.totalFees.pct256(disputesConfig.appealConfirmCollateralFactor); return nextRound; } /** * @dev Internal function to calculate the guardians number for the next regular round of a given round. This function assumes Court term is * up-to-date, that the next round of the one given is regular, and the given config corresponds to the draft term of the given round. * @param _round Round querying the guardians number of its next round * @param _config Disputes config at the draft term of the first round of the dispute * @return Guardians number for the next regular round of the given round */ function _getNextRegularRoundGuardiansNumber(AdjudicationRound storage _round, DisputesConfig memory _config) internal view returns (uint64) { // Guardians number are increased by a step factor on each appeal uint64 guardiansNumber = _round.guardiansNumber.mul(_config.appealStepFactor); // Make sure it's odd to enforce avoiding a tie. Note that it can happen if any of the guardians don't vote anyway. if (uint256(guardiansNumber) % 2 == 0) { guardiansNumber++; } return guardiansNumber; } /** * @dev Internal function to tell adjudication state of a round at a certain term. This function assumes the given round exists. * @param _dispute Dispute querying the adjudication round of * @param _roundId Identification number of the dispute round querying the adjudication round of * @param _termId Identification number of the term to be used for the different round phases durations * @param _config Disputes config at the draft term ID of the given dispute * @return Adjudication state of the requested dispute round for the given term */ function _adjudicationStateAt(Dispute storage _dispute, uint256 _roundId, uint64 _termId, DisputesConfig memory _config) internal view returns (AdjudicationState) { AdjudicationRound storage round = _dispute.rounds[_roundId]; // If the dispute is ruled or the given round is not the last one, we consider it ended uint256 numberOfRounds = _dispute.rounds.length; if (_dispute.state == DisputeState.Ruled || _roundId < numberOfRounds.sub(1)) { return AdjudicationState.Ended; } // If given term is before the actual term when the last round was finally drafted, then the last round adjudication state is invalid uint64 draftFinishedTermId = round.draftTermId.add(round.delayedTerms); if (_dispute.state == DisputeState.PreDraft || _termId < draftFinishedTermId) { return AdjudicationState.Invalid; } // If given term is before the reveal start term of the last round, then guardians are still allowed to commit votes for the last round uint64 revealStartTerm = draftFinishedTermId.add(_config.commitTerms); if (_termId < revealStartTerm) { return AdjudicationState.Committing; } // If given term is before the appeal start term of the last round, then guardians are still allowed to reveal votes for the last round uint64 appealStartTerm = revealStartTerm.add(_config.revealTerms); if (_termId < appealStartTerm) { return AdjudicationState.Revealing; } // If the max number of appeals has been reached, then the last round is the final round and can be considered ended bool maxAppealReached = numberOfRounds > _config.maxRegularAppealRounds; if (maxAppealReached) { return AdjudicationState.Ended; } // If the last round was not appealed yet, check if the confirmation period has started or not bool isLastRoundAppealed = _existsAppeal(round.appeal); uint64 appealConfirmationStartTerm = appealStartTerm.add(_config.appealTerms); if (!isLastRoundAppealed) { // If given term is before the appeal confirmation start term, then the last round can still be appealed. Otherwise, it is ended. if (_termId < appealConfirmationStartTerm) { return AdjudicationState.Appealing; } else { return AdjudicationState.Ended; } } // If the last round was appealed and the given term is before the appeal confirmation end term, then the last round appeal can still be // confirmed. Note that if the round being checked was already appealed and confirmed, it won't be the last round, thus it will be caught // above by the first check and considered 'Ended'. uint64 appealConfirmationEndTerm = appealConfirmationStartTerm.add(_config.appealConfirmTerms); if (_termId < appealConfirmationEndTerm) { return AdjudicationState.ConfirmingAppeal; } // If non of the above conditions have been met, the last round is considered ended return AdjudicationState.Ended; } /** * @dev Internal function to check if a certain appeal exists * @param _appeal Appeal to be checked * @return True if the given appeal has a maker address associated to it, false otherwise */ function _existsAppeal(Appeal storage _appeal) internal view returns (bool) { return _appeal.maker != address(0); } /** * @dev Internal function to check if a certain appeal has been confirmed * @param _appeal Appeal to be checked * @return True if the given appeal was confirmed, false otherwise */ function _isAppealConfirmed(Appeal storage _appeal) internal view returns (bool) { return _appeal.taker != address(0); } /** * @dev Internal function to check if a certain dispute round exists, it reverts if it doesn't * @param _dispute Dispute to be checked * @param _roundId Identification number of the dispute round to be checked */ function _checkRoundExists(Dispute storage _dispute, uint256 _roundId) internal view { require(_roundId < _dispute.rounds.length, ERROR_ROUND_DOES_NOT_EXIST); } /** * @dev Internal function to fetch a dispute * @param _disputeId Identification number of the dispute to be fetched * @return Dispute instance requested */ function _getDispute(uint256 _disputeId) internal view returns (Dispute storage) { require(_disputeId < disputes.length, ERROR_DISPUTE_DOES_NOT_EXIST); return disputes[_disputeId]; } /** * @dev Internal function to get the Court config used for a dispute * @param _dispute Dispute querying the Court config of * @return Court config used for the given dispute */ function _getDisputeConfig(Dispute storage _dispute) internal view returns (Config memory) { // Note that it is safe to access a Court config directly for a past term return _getConfigAt(_dispute.createTermId); } /** * @dev Internal function to fetch a dispute and round * @param _disputeId Identification number of the dispute to be fetched * @param _roundId Identification number of the round to be fetched * @return dispute Dispute instance requested * @return round Round instance requested */ function _getDisputeAndRound(uint256 _disputeId, uint256 _roundId) internal view returns (Dispute storage dispute, AdjudicationRound storage round) { dispute = _getDispute(_disputeId); _checkRoundExists(dispute, _roundId); round = dispute.rounds[_roundId]; } /** * @dev Internal function to fetch a dispute with its config * @param _disputeId Identification number of the dispute to be fetched * @return dispute Dispute instance requested * @return config Court config used for the given dispute */ function _getDisputeWithConfig(uint256 _disputeId) internal view returns (Dispute storage dispute, Config memory config) { dispute = _getDispute(_disputeId); config = _getDisputeConfig(dispute); } /** * @dev Internal function to fetch a dispute and round with its config * @param _disputeId Identification number of the dispute to be fetched * @param _roundId Identification number of the round to be fetched * @return dispute Dispute instance requested * @return round Round instance requested * @return config Court config used for the given dispute */ function _getDisputeAndRoundWithConfig(uint256 _disputeId, uint256 _roundId) internal view returns (Dispute storage dispute, AdjudicationRound storage round, Config memory config) { (dispute, round) = _getDisputeAndRound(_disputeId, _roundId); config = _getDisputeConfig(dispute); } /** * @dev Internal function to get the dispute round of a certain vote identification number * @param _voteId Identification number of the vote querying the dispute round of * @return dispute Dispute for the given vote * @return roundId Identification number of the dispute round for the given vote * @return config Court config used for the given dispute */ function _decodeVoteId(uint256 _voteId) internal view returns (Dispute storage dispute, uint256 roundId, Config memory config) { uint256 disputeId = _voteId >> 128; roundId = _voteId & VOTE_ID_MASK; dispute = _getDispute(disputeId); _checkRoundExists(dispute, roundId); config = _getDisputeConfig(dispute); } /** * @dev Internal function to get the identification number of the vote of a certain dispute round * @param _disputeId Identification number of the dispute querying the vote ID of * @param _roundId Identification number of the dispute round querying the vote ID of * @return Identification number of the vote of the requested dispute round */ function _getVoteId(uint256 _disputeId, uint256 _roundId) internal pure returns (uint256) { return (_disputeId << 128) + _roundId; } /** * @dev Assumes round.coherentGuardians is greater than zero * @param _round Round which the weighted amount is computed for * @param _guardianState Guardian with state which the weighted amount is computed for * @param _amount Amount to be weighted * @return Weighted amount for a guardian in a round in relation to total amount of coherent guardians */ function _getRoundWeightedAmount( AdjudicationRound storage _round, GuardianState storage _guardianState, uint256 _amount ) internal view returns (uint256) { return _amount.mul(_guardianState.weight) / _round.coherentGuardians; } /** * @dev Internal function to get fees information for regular rounds for a certain term. This function assumes Court term is up-to-date. * @param _config Court config to use in order to get fees * @param _guardiansNumber Number of guardians participating in the round being queried * @return feeToken ERC20 token used for the fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of a round * @return totalFees Total amount of fees for a regular round at the given term */ function _getRegularRoundFees(FeesConfig memory _config, uint64 _guardiansNumber) internal pure returns (IERC20 feeToken, uint256 guardianFees, uint256 totalFees) { feeToken = _config.token; // For regular rounds the fees for each guardian is constant and given by the config of the round guardianFees = uint256(_guardiansNumber).mul(_config.guardianFee); // The total fees for regular rounds also considers the number of drafts and settles uint256 draftAndSettleFees = (_config.draftFee.add(_config.settleFee)).mul(uint256(_guardiansNumber)); totalFees = guardianFees.add(draftAndSettleFees); } /** * @dev Internal function to get fees information for final rounds for a certain term. This function assumes Court term is up-to-date. * @param _config Court config to use in order to get fees * @param _guardiansNumber Number of guardians participating in the round being queried * @return feeToken ERC20 token used for the fees * @return guardianFees Total amount of fees corresponding to the guardians at the given term * @return totalFees Total amount of fees for a final round at the given term */ function _getFinalRoundFees(FeesConfig memory _config, uint64 _guardiansNumber) internal pure returns (IERC20 feeToken, uint256 guardianFees, uint256 totalFees) { feeToken = _config.token; // For final rounds, the guardians number is computed as the number of times the registry's minimum active balance is held in the registry // itself, multiplied by a precision factor. To avoid requesting a huge amount of fees, a final round discount is applied for each guardian. guardianFees = (uint256(_guardiansNumber).mul(_config.guardianFee) / FINAL_ROUND_WEIGHT_PRECISION).pct(_config.finalRoundReduction); // There is no draft and no extra settle fees considered for final rounds totalFees = guardianFees; } /** * @dev Internal function to tell whether a round is regular or final. This function assumes the given round exists. * @param _roundId Identification number of the round to be checked * @param _config Court config to use in order to check if the given round is regular or final * @return True if the given round is regular, false in case its a final round */ function _isRegularRound(uint256 _roundId, Config memory _config) internal pure returns (bool) { return _roundId < _config.disputes.maxRegularAppealRounds; } /** * @dev Calculate the number of times that an amount contains the min active balance (multiplied by precision). * Used to get the guardian weight for the final round. Note that for the final round the weight of * each guardian is equal to the number of times the min active balance the guardian has, multiplied by a precision * factor to deal with division rounding. * @param _activeBalance Guardian's or total active balance * @param _minActiveBalance Minimum amount of guardian tokens that can be activated * @return Number of times that the active balance contains the min active balance (multiplied by precision) */ function _getMinActiveBalanceMultiple(uint256 _activeBalance, uint256 _minActiveBalance) internal pure returns (uint64) { // Note that guardians may not reach the minimum active balance since some might have been slashed. If that occurs, // these guardians cannot vote in the final round. if (_activeBalance < _minActiveBalance) { return 0; } // Otherwise, return the times the active balance of the guardian fits in the min active balance, multiplying // it by a round factor to ensure a better precision rounding. return (FINAL_ROUND_WEIGHT_PRECISION.mul(_activeBalance) / _minActiveBalance).toUint64(); } /** * @dev Private function to build params to call for a draft. It assumes the given data is correct. * @param _disputeId Identification number of the dispute to be drafted * @param _roundId Identification number of the round to be drafted * @param _termId Identification number of the current term of the Court * @param _draftTermRandomness Randomness of the term in which the dispute was requested to be drafted * @param _config Draft config of the Court at the draft term * @return Draft params object */ function _buildDraftParams(uint256 _disputeId, uint256 _roundId, uint64 _termId, bytes32 _draftTermRandomness, DraftConfig memory _config) private pure returns (DraftParams memory) { return DraftParams({ disputeId: _disputeId, roundId: _roundId, termId: _termId, draftTermRandomness: _draftTermRandomness, config: _config }); } /** * @dev Private function to draft guardians for a given dispute and round. It assumes the given data is correct. * @param _round Round of the dispute to be drafted * @param _draftParams Draft params to be used for the draft * @return True if all the requested guardians for the given round were drafted, false otherwise */ function _draft(AdjudicationRound storage _round, DraftParams memory _draftParams) private returns (bool) { uint64 guardiansNumber = _round.guardiansNumber; uint64 selectedGuardians = _round.selectedGuardians; uint64 maxGuardiansPerBatch = maxGuardiansPerDraftBatch; uint64 guardiansToBeDrafted = guardiansNumber.sub(selectedGuardians); // Draft the min number of guardians between the one requested by the sender and the one requested by the sender uint64 requestedGuardians = guardiansToBeDrafted < maxGuardiansPerBatch ? guardiansToBeDrafted : maxGuardiansPerBatch; // Pack draft params uint256[7] memory params = [ uint256(_draftParams.draftTermRandomness), _draftParams.disputeId, uint256(_draftParams.termId), uint256(selectedGuardians), uint256(requestedGuardians), uint256(guardiansNumber), uint256(_draftParams.config.penaltyPct) ]; // Draft guardians for the requested round IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); (address[] memory guardians, uint256 draftedGuardians) = guardiansRegistry.draft(params); // Update round with drafted guardians information uint64 newSelectedGuardians = selectedGuardians.add(uint64(draftedGuardians)); _round.selectedGuardians = newSelectedGuardians; _updateRoundDraftedGuardians(_draftParams.disputeId, _draftParams.roundId, _round, guardians, draftedGuardians); bool draftEnded = newSelectedGuardians == guardiansNumber; // Transfer fees corresponding to the actual number of drafted guardians uint256 draftFees = _draftParams.config.draftFee.mul(draftedGuardians); _treasury().assign(_draftParams.config.feeToken, msg.sender, draftFees); return draftEnded; } /** * @dev Private function to update the drafted guardians' weight for the given round * @param _disputeId Identification number of the dispute being drafted * @param _roundId Identification number of the round being drafted * @param _round Adjudication round that was drafted * @param _guardians List of guardians addresses that were drafted for the given round * @param _draftedGuardians Number of guardians that were drafted for the given round. Note that this number may not necessarily be equal to the * given list of guardians since the draft could potentially return less guardians than the requested amount. */ function _updateRoundDraftedGuardians( uint256 _disputeId, uint256 _roundId, AdjudicationRound storage _round, address[] memory _guardians, uint256 _draftedGuardians ) private { for (uint256 i = 0; i < _draftedGuardians; i++) { address guardian = _guardians[i]; GuardianState storage guardianState = _round.guardiansStates[guardian]; // If the guardian was already registered in the list, then don't add it twice if (uint256(guardianState.weight) == 0) { _round.guardians.push(guardian); } guardianState.weight = guardianState.weight.add(1); emit GuardianDrafted(_disputeId, _roundId, guardian); } } /** * @dev Private function to burn the collected for a certain round in case there were no coherent guardians * @param _dispute Dispute to settle penalties for * @param _round Dispute round to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _courtTreasury Treasury module to refund the corresponding guardian fees * @param _feeToken ERC20 token to be used for the fees corresponding to the draft term of the given dispute round * @param _collectedTokens Amount of tokens collected during the given dispute round */ function _burnCollectedTokensIfNecessary( Dispute storage _dispute, AdjudicationRound storage _round, uint256 _roundId, ITreasury _courtTreasury, IERC20 _feeToken, uint256 _collectedTokens ) private { // If there was at least one guardian voting in favor of the winning ruling, return if (_round.coherentGuardians > 0) { return; } // Burn all the collected tokens of the guardians to be slashed. Note that this will happen only when there were no guardians voting // in favor of the final winning outcome. Otherwise, these will be re-distributed between the winning guardians in `settleReward` // instead of being burned. if (_collectedTokens > 0) { IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); guardiansRegistry.burnTokens(_collectedTokens); } // Reimburse guardian fees to the Arbtirable subject for round 0 or to the previous appeal parties for other rounds. // Note that if the given round is not the first round, we can ensure there was an appeal in the previous round. if (_roundId == 0) { _courtTreasury.assign(_feeToken, address(_dispute.subject), _round.guardianFees); } else { uint256 refundFees = _round.guardianFees / 2; Appeal storage triggeringAppeal = _dispute.rounds[_roundId - 1].appeal; _courtTreasury.assign(_feeToken, triggeringAppeal.maker, refundFees); _courtTreasury.assign(_feeToken, triggeringAppeal.taker, refundFees); } } /** * @dev Private function only used in the constructor to skip a given number of disputes * @param _skippedDisputes Number of disputes to be skipped */ function _skipDisputes(uint256 _skippedDisputes) private { assert(disputes.length == 0); disputes.length = _skippedDisputes; } }
* @dev Assumes round.coherentGuardians is greater than zero @param _round Round which the weighted amount is computed for @param _guardianState Guardian with state which the weighted amount is computed for @param _amount Amount to be weighted @return Weighted amount for a guardian in a round in relation to total amount of coherent guardians/
function _getRoundWeightedAmount( AdjudicationRound storage _round, GuardianState storage _guardianState, uint256 _amount ) internal view returns (uint256) { return _amount.mul(_guardianState.weight) / _round.coherentGuardians; }
10,544,642
[ 1, 2610, 6411, 3643, 18, 2894, 1614, 319, 16709, 19657, 353, 6802, 2353, 3634, 225, 389, 2260, 11370, 1492, 326, 13747, 3844, 353, 8470, 364, 225, 389, 24594, 2779, 1119, 22809, 2779, 598, 919, 1492, 326, 13747, 3844, 353, 8470, 364, 225, 389, 8949, 16811, 358, 506, 13747, 327, 15437, 329, 3844, 364, 279, 11026, 2779, 316, 279, 3643, 316, 2533, 358, 2078, 3844, 434, 1825, 1614, 319, 11026, 19657, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 11066, 6544, 329, 6275, 12, 203, 3639, 4052, 78, 1100, 829, 11066, 2502, 389, 2260, 16, 203, 3639, 22809, 2779, 1119, 2502, 389, 24594, 2779, 1119, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 8949, 18, 16411, 24899, 24594, 2779, 1119, 18, 4865, 13, 342, 389, 2260, 18, 2894, 1614, 319, 16709, 19657, 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 ]
./full_match/1/0xcDA39B74054EFFB230156f21b334E50295Ca8df4/sources/contracts/strategies/AaveFlashloanStrategy/AaveFlashloanStrategy.sol
@notice Deposit `want` tokens in Aave and start earning interests @param amount Amount to be deposited @return amount The amount deposited
function _depositCollateral(uint256 amount) internal returns (uint256) { if (amount == 0) return 0; _lendingPool.deposit(address(want), amount, address(this), _referral); return amount; }
9,603,132
[ 1, 758, 1724, 1375, 17369, 68, 2430, 316, 432, 836, 471, 787, 425, 9542, 16513, 87, 225, 3844, 16811, 358, 506, 443, 1724, 329, 327, 3844, 1021, 3844, 443, 1724, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 323, 1724, 13535, 2045, 287, 12, 11890, 5034, 3844, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 8949, 422, 374, 13, 327, 374, 31, 203, 3639, 389, 80, 2846, 2864, 18, 323, 1724, 12, 2867, 12, 17369, 3631, 3844, 16, 1758, 12, 2211, 3631, 389, 1734, 29084, 1769, 203, 3639, 327, 3844, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; //////////////////////////////////////////////////////////////////////////////// library SafeMath // This library is not used systematically since it tends to create "Infinite gas" functions and consumes too many gas { //------------------ 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) { return a/b; } //-------------------------------------------------------------------------- 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; } } //////////////////////////////////////////////////////////////////////////////// contract ERC20 { using SafeMath for uint256; //----- VARIABLES address public owner; // Owner of this contract address public admin; // The one who is allowed to do changes address public mazler; mapping(address => uint256) balances; // Maintain balance in a mapping mapping(address => mapping (address => uint256)) allowances; // Allowances index-1 = Owner account index-2 = spender account //------ TOKEN SPECIFICATION string public name = "DIAM"; string public symbol = "DIAM"; uint256 public constant decimals = 5; // Handle the coin as FIAT (2 decimals). ETH Handles 18 decimal places uint256 public constant initSupply = 150000000 * 10**decimals; //150000000 * 10**decimals; // 10**18 max uint256 public totalSoldByOwner=0; // Not from ERC-20 specification, but help for the totalSupply management later //----- uint256 public totalSupply; uint256 mazl = 10; uint256 vScale = 10000; //-------------------------------------------------------------------------- modifier onlyOwner() { require(msg.sender==owner); _; } modifier onlyAdmin() { require(msg.sender==admin); _; } //----- EVENTS event Transfer(address indexed fromAddr, address indexed toAddr, uint256 amount); event Approval(address indexed _owner, address indexed _spender, uint256 amount); event OnOwnershipTransfered(address oldOwnerWallet, address newOwnerWallet); event OnAdminUserChanged( address oldAdminWalet, address newAdminWallet); event OnVautingUserChanged( address oldWallet, address newWallet); //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- constructor() public { owner = msg.sender; admin = owner; mazler = owner; balances[owner] = initSupply; // send the tokens to the owner totalSupply = initSupply; } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //----- ERC20 FUNCTIONS //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function balanceOf(address walletAddress) public view /*constant*/ returns (uint256 balance) { return balances[walletAddress]; } //-------------------------------------------------------------------------- function transfer(address toAddr, uint256 amountInWei) public returns (bool) { uint256 baseAmount; uint256 finalAmount; uint256 addAmountInWei; require(toAddr!=address(0x0) && toAddr!=msg.sender && amountInWei!=0 && amountInWei<=balances[msg.sender]); //----- Reduce gas consumption of ==> balances[msg.sender] = balances[msg.sender].sub(amountInWei); baseAmount = balances[msg.sender]; finalAmount = baseAmount - amountInWei; assert(finalAmount <= baseAmount); balances[msg.sender] = finalAmount; //----- Reduce gas consumption of ==> balances[toAddr] = balances[toAddr].add(amountInWei); baseAmount = balances[toAddr]; addAmountInWei = manageMazl(toAddr, amountInWei); finalAmount = baseAmount + addAmountInWei; assert(finalAmount >= baseAmount); balances[toAddr] = finalAmount; //----- if (msg.sender==owner) { totalSoldByOwner += amountInWei; } //----- emit Transfer(msg.sender, toAddr, addAmountInWei /*amountInWei*/); return true; } //-------------------------------------------------------------------------- function allowance(address walletAddress, address spender) public view/*constant*/ returns (uint remaining) { return allowances[walletAddress][spender]; } //-------------------------------------------------------------------------- function transferFrom(address fromAddr, address toAddr, uint256 amountInWei) public returns (bool) { require(amountInWei!=0 && balances[fromAddr] >= amountInWei && allowances[fromAddr][msg.sender] >= amountInWei); //----- balances[fromAddr] = balances[fromAddr].sub(amountInWei); uint256 baseAmount = balances[fromAddr]; uint256 finalAmount = baseAmount - amountInWei; assert(finalAmount <= baseAmount); balances[fromAddr] = finalAmount; //----- balances[toAddr] = balances[toAddr].add(amountInWei); baseAmount = balances[toAddr]; finalAmount = baseAmount + amountInWei; assert(finalAmount >= baseAmount); balances[toAddr] = finalAmount; //----- allowances[fromAddr][msg.sender] = allowances[fromAddr][msg.sender].sub(amountInWei); baseAmount = allowances[fromAddr][msg.sender]; finalAmount = baseAmount - amountInWei; assert(finalAmount <= baseAmount); allowances[fromAddr][msg.sender] = finalAmount; //----- emit Transfer(fromAddr, toAddr, amountInWei); return true; } //-------------------------------------------------------------------------- function approve(address spender, uint256 amountInWei) public returns (bool) { allowances[msg.sender][spender] = amountInWei; emit Approval(msg.sender, spender, amountInWei); return true; } //-------------------------------------------------------------------------- function() external { assert(true == false); // If Ether is sent to this address, don't handle it } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function transferOwnership(address newOwner) public onlyOwner // @param newOwner The address to transfer ownership to. { require(newOwner != address(0)); emit OnOwnershipTransfered(owner, newOwner); owner = newOwner; totalSoldByOwner = 0; } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function manageMazl(address walletTo, uint256 amountInWei) /*private*/ public returns(uint256) { uint256 addAmountInWei; uint256 baseAmount; uint256 finalAmount; uint256 mazlInWei; addAmountInWei = amountInWei; if (msg.sender!=admin && msg.sender!=owner) { mazlInWei = (amountInWei * mazl) / vScale; if (mazlInWei <= amountInWei) { addAmountInWei = amountInWei - mazlInWei; baseAmount = balances[mazler]; finalAmount = baseAmount + mazlInWei; if (finalAmount>=baseAmount) { balances[mazler] = finalAmount; emit Transfer(walletTo, mazler, mazlInWei); } } } return addAmountInWei; } //-------------------------------------------------------------------------- function changeAdminUser(address newAdminAddress) public onlyOwner returns(uint256) { require(newAdminAddress!=address(0x0)); emit OnAdminUserChanged(admin, newAdminAddress); admin = newAdminAddress; return 1; // for API use } //-------------------------------------------------------------------------- function changeMazlUser(address newAddress) public onlyOwner returns(uint256) { require(newAddress!=address(0x0)); emit OnVautingUserChanged(admin, newAddress); mazler = newAddress; return 1; // for API use } } //////////////////////////////////////////////////////////////////////////////// contract DiamondTransaction is ERC20 { struct TDiamondTransaction { bool isBuyTransaction; // Tells if this transaction was for us to buy diamonds or just to sell diamonds uint authorityId; // id(0)=GIA uint certificate; // Can be a direct certificat value (from GIA), or an HEX value if alpnumeric from other authorities uint providerId; // The vendor/Acqueror of the TTransaction uint vaultId; // ID of the secured vault used in our database uint sourceId; // Diamcoin: 0 partners > 0 uint caratAmount; // 3 decimals value flatten to an integer uint tokenAmount; // uint tokenId; // ID of the token used to sold. IT should be id=0 for Diamcoin uint timestamp; // When the transaction occurred bool isValid; // Should always be TRUE (=1) } mapping(uint256 => TDiamondTransaction) diamondTransactions; uint256[] diamondTransactionIds; event OnDiamondBoughTransaction ( uint256 authorityId, uint256 certificate, uint256 providerId, uint256 vaultId, uint256 caratAmount, uint256 tokenAmount, uint256 tokenId, uint256 timestamp ); event OnDiamondSoldTransaction ( uint256 authorityId, uint256 certificate, uint256 providerId, uint256 vaultId, uint256 caratAmount, uint256 tokenAmount, uint256 tokenId, uint256 timestamp ); //-------------------------------------------------------------------------- function storeDiamondTransaction(bool isBuy, uint256 indexInOurDb, uint256 authorityId, uint256 certificate, uint256 providerId, uint256 vaultId, uint256 caratAmount, uint256 tokenAmount, uint256 sourceId, uint256 tokenId) public onlyAdmin returns(bool) { TDiamondTransaction memory item; item.isBuyTransaction = isBuy; item.authorityId = authorityId; item.certificate = certificate; item.providerId = providerId; item.vaultId = vaultId; item.caratAmount = caratAmount; item.tokenAmount = tokenAmount; item.tokenId = tokenId; item.timestamp = now; item.isValid = true; item.sourceId = sourceId; diamondTransactions[indexInOurDb] = item; diamondTransactionIds.push(indexInOurDb)-1; if (isBuy) { emit OnDiamondBoughTransaction(authorityId, certificate, providerId, vaultId, caratAmount, tokenAmount, tokenId, now); } else { emit OnDiamondSoldTransaction( authorityId, certificate, providerId, vaultId, caratAmount, tokenAmount, tokenId, now); } return true; // this is only for our external API use } //-------------------------------------------------------------------------- function getDiamondTransaction(uint256 transactionId) public view returns(/*uint256,*/uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return ( (item.isBuyTransaction)?1:0, item.authorityId, item.certificate, item.providerId, item.vaultId, item.caratAmount, (item.isValid?1:0), item.tokenId, item.timestamp, item.sourceId ); } //-------------------------------------------------------------------------- function getEntitiesFromDiamondTransaction(uint256 transactionId) public view returns(uint256,uint256,uint256,uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return // If you want to know who was involved in that transaction ( item.authorityId, item.certificate, item.providerId, item.vaultId ); } //-------------------------------------------------------------------------- function getAmountsAndTypesFromDiamondTransaction(uint256 transactionId) public view returns(uint256,uint256,uint256,uint256,uint256,uint256,uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return ( (item.isBuyTransaction)?1:0, item.caratAmount, item.tokenAmount, item.tokenId, (item.isValid?1:0), item.timestamp, item.sourceId ); } //-------------------------------------------------------------------------- function getCaratAmountFromDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return item.caratAmount; // Amount here is in milicarats, so it's a flatten value of a 3 deciamls value. ie: 1.546 carats is 1546 here } //-------------------------------------------------------------------------- function getTokenAmountFromDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return item.tokenAmount; } //-------------------------------------------------------------------------- function isValidDiamondTransaction(uint256 transactionId) public view returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; return (item.isValid?1:0); } //-------------------------------------------------------------------------- function changeDiamondTransactionStatus(uint256 transactionId, uint256 newStatus) public view onlyAdmin returns(uint256) { TDiamondTransaction memory item; item = diamondTransactions[transactionId]; item.isValid = (newStatus==0) ? false:false; // in case there was any issue with the transaction, set it as invalid (=2) or invalid=0 return 1; // needed for our API } //-------------------------------------------------------------------------- function getDiamondTransactionCount() public view returns(uint256) { return diamondTransactionIds.length; } //-------------------------------------------------------------------------- function getDiamondTransactionAtIndex(uint256 index) public view returns(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) { TDiamondTransaction memory DT; uint256 txId; if (index<diamondTransactionIds.length) { txId = diamondTransactionIds[index]; DT = diamondTransactions[txId]; return ( (DT.isBuyTransaction)?1:0, DT.authorityId, DT.certificate, DT.providerId, DT.vaultId, DT.caratAmount, (DT.isValid?1:0), DT.tokenId, DT.timestamp, DT.sourceId ); } return (0,0,0,0,0,0,0,0,0,0); } } //////////////////////////////////////////////////////////////////////////////// contract SocialLocker is DiamondTransaction { uint256 public minVotesCount = 20; bool public isSocialLockerEnabled = true; mapping(address => bool) voteLockedWallets; mapping(address => uint256) refundTotalVotes; mapping(address => uint256) unlockingTotalVotes; mapping(address => bool) forbiddenVoters; mapping(address => mapping(address => bool)) votersMap; // Used to avoid one voter to vote twice on the same user event OnLockedWallet( address lockedWallet, uint256 timestamp); event OnVotedForRefund( address voter, address walletToVoteFor, uint256 voteScore, uint256 maxVotes); // People has voted to refund all tokens from the involved wallet. it's a social voting event OnVotedForUnlocking(address voter, address walletToVoteFor, uint256 voteScore, uint256 maxVotes); // People has voted to unlock this wallet event OnVoterBannished( address voter); event OnVoterAllowed( address voter); event OnWalletBlocked( address wallet); // The wallet will no more be allowed to send nor receive tokens event OnSocialLockerWalletDepleted(address possibleFraudster); event OnSocialLockerWalletUnlocked(address possibleFraudster); event OnSocialLockerStateChanged(bool oldState, bool newState); event OnSocialLockerChangeMinVoteCount(uint oldMinVoteCount, uint newMinVoteCount); event OnWalletTaggedForSocialLocking(address taggedWallet); //-------------------------------------------------------------------------- function changeSocialLockerState(bool newState) public onlyAdmin returns(uint256) { emit OnSocialLockerStateChanged(isSocialLockerEnabled, newState); isSocialLockerEnabled = newState; return 1; } //-------------------------------------------------------------------------- function changeMinVoteCount(uint256 newMinVoteCount) public onlyAdmin returns(uint256) { emit OnSocialLockerChangeMinVoteCount(minVotesCount, newMinVoteCount); minVotesCount = newMinVoteCount; return 1; } //-------------------------------------------------------------------------- function tagWalletForVoting(address walletToTag) public onlyAdmin returns(uint256) { voteLockedWallets[walletToTag] = true; // now people can vote for a refund or to unlock this wallet unlockingTotalVotes[walletToTag] = 0; // no votes yet on this refundTotalVotes[walletToTag] = 0; // no vote yet emit OnWalletTaggedForSocialLocking(walletToTag); return 1; } //-------------------------------------------------------------------------- function voteForARefund(address voter, address possibleFraudster) public returns(uint256) { uint256 currentVoteCount; uint256 sum; uint256 baseAmount; uint256 finalAmount; require(voteLockedWallets[possibleFraudster] && !forbiddenVoters[voter] && !votersMap[possibleFraudster][voter] && isSocialLockerEnabled); // Don't vote on wallets not yet locked by ADMIN. To avoid abuse and security issues votersMap[possibleFraudster][voter] = true; // Ok, this voter just voted, don't allow anymore votes from him on the possibleFraudster currentVoteCount = refundTotalVotes[possibleFraudster]; sum = currentVoteCount + 1; assert(currentVoteCount<sum); refundTotalVotes[possibleFraudster] = sum; emit OnVotedForRefund(voter, possibleFraudster, sum, minVotesCount); // People has voted to refund all tokens from the involved wallet. it's a social voting //----- if (sum>=minVotesCount) // The VOTE is Finished!!! { baseAmount = balances[owner]; finalAmount = baseAmount + balances[possibleFraudster]; assert(finalAmount >= baseAmount); balances[owner] = finalAmount; // The official Token owner receives back the token (voted as to be refunded) balances[possibleFraudster] = 0; // Sorry scammer, but the vote said you won't have even 1 token in your wallet! voteLockedWallets[possibleFraudster] = false; emit Transfer(possibleFraudster, owner, balances[possibleFraudster]); } return 1; } //-------------------------------------------------------------------------- function voteForUnlocking(address voter, address possibleFraudster) public returns(uint256) { uint256 currentVoteCount; uint256 sum; require(voteLockedWallets[possibleFraudster] && !forbiddenVoters[voter] && !votersMap[possibleFraudster][voter] && isSocialLockerEnabled); // Don't vote on wallets not yet locked by ADMIN. To avoid abuse and security issues votersMap[possibleFraudster][voter] = true; // don't let the voter votes again for this possibleFraudster currentVoteCount = unlockingTotalVotes[possibleFraudster]; sum = currentVoteCount + 1; assert(currentVoteCount<sum); unlockingTotalVotes[possibleFraudster] = sum; emit OnVotedForUnlocking(voter, possibleFraudster, sum, minVotesCount); // People has voted to refund all tokens from the involved wallet. it's a social voting //----- if (sum>=minVotesCount) // The VOTE is Finished!!! { voteLockedWallets[possibleFraudster] = false; // Redemption allowed by the crowd } return 1; } //-------------------------------------------------------------------------- function banVoter(address voter) public onlyAdmin returns(uint256) { forbiddenVoters[voter] = true; // this user cannot vote anymore. A possible abuser emit OnVoterBannished(voter); } //-------------------------------------------------------------------------- function allowVoter(address voter) public onlyAdmin returns(uint256) { forbiddenVoters[voter] = false; // this user cannot vote anymore. A possible abuser emit OnVoterAllowed(voter); } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- } //////////////////////////////////////////////////////////////////////////////// contract Token is SocialLocker { address public validator; // Address of the guy who will validate any extend/reduce query. so it's considered as Admin2 here. Adm uint256 public minDelayBeforeStockChange = 6*3600; // StockReduce allowed EVERY 6 hours only uint256 public maxReduceInUnit = 5000000; uint256 public maxReduce = maxReduceInUnit * 10**decimals; // Don't allow a supply decrease if above this amount' uint256 public maxExtendInUnit = maxReduceInUnit; uint256 public maxExtend = maxExtendInUnit * 10**decimals; // Don't allow a supply decrease if above this amount' uint256 constant decimalMultiplicator = 10**decimals; uint256 lastReduceCallTime = 0; bool public isReduceStockValidated = false; /// A validator (=2nd admin) needs to confitm the action before changing the stock quantity bool public isExtendStockValidated = false; /// same... uint256 public reduceVolumeInUnit = 0; /// Used when asking to reduce amount of token. validator needs to confirm first! uint256 public extendVolumeInUnit = 0; /// Used when asking to extend amount of token. validator needs to confirm first! //----- modifier onlyValidator() { require(msg.sender==validator); _; } //----- event OnStockVolumeExtended(uint256 volumeInUnit, uint256 volumeInDecimal, uint256 newTotalSupply); event OnStockVolumeReduced( uint256 volumeInUnit, uint256 volumeInDecimal, uint256 newTotalSupply); event OnErrorLog(string functionName, string errorMsg); event OnLogNumber(string section, uint256 value); event OnMaxReduceChanged(uint256 maxReduceInUnit, uint256 oldQuantity); event OnMaxExtendChanged(uint256 maxExtendInUnit, uint256 oldQuantity); event OnValidationUserChanged(address oldValidator, address newValidator); //-------------------------------------------------------------------------- constructor() public { validator = owner; } //-------------------------------------------------------------------------- function changeMaxReduceQuantity(uint256 newQuantityInUnit) public onlyAdmin returns(uint256) { uint256 oldQuantity = maxReduceInUnit; maxReduceInUnit = newQuantityInUnit; maxReduce = maxReduceInUnit * 10**decimals; emit OnMaxReduceChanged(maxReduceInUnit, oldQuantity); return 1; // used for the API (outside the smartcontract) } //-------------------------------------------------------------------------- function changeMaxExtendQuantity(uint256 newQuantityInUnit) public onlyAdmin returns(uint256) { uint256 oldQuantity = maxExtendInUnit; maxExtendInUnit = newQuantityInUnit; maxExtend = maxExtendInUnit * 10**decimals; emit OnMaxExtendChanged(maxExtendInUnit, oldQuantity); return 1; // used for the API (outside the smartcontract) } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function changeValidationUser(address newValidatorAddress) public onlyOwner returns(uint256) // The validation user is the guy who will finally confirm a token reduce or a token extend { require(newValidatorAddress!=address(0x0)); emit OnValidationUserChanged(validator, newValidatorAddress); validator = newValidatorAddress; return 1; } //-------------------------------------------------------------------------- function changeMinDelayBeforeStockChange(uint256 newDelayInSecond) public onlyAdmin returns(uint256) { if (newDelayInSecond<60) return 0; // not less than one minute else if (newDelayInSecond>24*3600) return 0; // not more than 24H of waiting minDelayBeforeStockChange = newDelayInSecond; emit OnLogNumber("changeMinDelayBeforeReduce", newDelayInSecond); return 1; // for API use } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function requestExtendStock(uint256 volumeInUnit) public onlyAdmin returns(uint256) { require(volumeInUnit<=maxExtendInUnit); isExtendStockValidated = true; extendVolumeInUnit = volumeInUnit; // If a request was already done, the volume will be changed with this one return 1; // for API use } //-------------------------------------------------------------------------- function cancelExtendStock() public onlyValidator returns(uint256) { isExtendStockValidated = false; // Cancel any request posted by admin return 1; // for API use } //-------------------------------------------------------------------------- function extendStock(uint256 volumeAllowedInUnit) public onlyValidator returns(uint256,uint256,uint256,uint256) { if (!isExtendStockValidated) // Validator (admin2) must validate the query first! { emit OnErrorLog("extendStock", "Request not validated yet"); return (0,0,0,0); } require(extendVolumeInUnit<=maxExtendInUnit); require(volumeAllowedInUnit==extendVolumeInUnit); // Don't allow the admin set arbritrary volume before validation //----- uint256 extraVolumeInDecimal = extendVolumeInUnit * decimalMultiplicator; // value in WEI //----- totalSupply = totalSupply.add(extraVolumeInDecimal); uint256 baseAmount = totalSupply; uint256 finalAmount = baseAmount + extraVolumeInDecimal; assert(finalAmount >= baseAmount); totalSupply = finalAmount; //----- balances[owner] = balances[owner].add(extraVolumeInDecimal); baseAmount = balances[owner]; finalAmount = baseAmount + extraVolumeInDecimal; assert(finalAmount >= baseAmount); balances[owner] = finalAmount; //----- isExtendStockValidated = false; // reset for the next extend request emit OnStockVolumeExtended(extendVolumeInUnit, extraVolumeInDecimal, totalSupply); return ( extendVolumeInUnit, extraVolumeInDecimal, balances[owner], totalSupply ); // origin:0 OWNER origin:1 AN_EXCHANGE } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- function requestReduceStock(uint256 volumeInUnit) public onlyAdmin returns(uint256) { require(volumeInUnit<=maxReduceInUnit); isReduceStockValidated = true; reduceVolumeInUnit = volumeInUnit; // If a request was already done, the volume will be changed with this one return 1; // for API use } //-------------------------------------------------------------------------- function cancelReduceStock() public onlyValidator returns(uint256) { isReduceStockValidated = false; // Cancel any request posted by admin return 1; // for API use } //-------------------------------------------------------------------------- function reduceStock(uint256 volumeAllowedInUnit) public onlyValidator returns(uint256,uint256,uint256,uint256) { if (!isReduceStockValidated) // Validator (admin2) must validate the query first! { emit OnErrorLog("reduceStock", "Request not validated yet"); return (0,0,0,0); } require(reduceVolumeInUnit<=maxReduceInUnit); require(volumeAllowedInUnit==reduceVolumeInUnit); // Don't allow the admin set arbritrary volume before validation if (!isReduceAllowedNow()) { return (0,0,0,0); } lastReduceCallTime = now; //----- uint256 reducedVolumeInDecimal = reduceVolumeInUnit * decimalMultiplicator; // value in WEI //----- totalSupply = totalSupply.sub(reducedVolumeInDecimal); uint256 baseAmount = totalSupply; uint256 finalAmount = baseAmount - reducedVolumeInDecimal; assert(finalAmount <= baseAmount); totalSupply = finalAmount; //----- balances[owner] = balances[owner].sub(reducedVolumeInDecimal); baseAmount = balances[owner]; finalAmount = baseAmount - reducedVolumeInDecimal; assert(finalAmount <= baseAmount); balances[owner] = finalAmount; //----- emit OnStockVolumeReduced(reduceVolumeInUnit, reducedVolumeInDecimal, totalSupply); return ( reduceVolumeInUnit, reducedVolumeInDecimal, balances[owner], totalSupply ); } //-------------------------------------------------------------------------- function isReduceAllowedNow() public view returns(bool) { uint256 delay = now - lastReduceCallTime; return (delay >= minDelayBeforeStockChange); } //-------------------------------------------------------------------------- function getStockBalance() public view returns(uint256) { return totalSupply; } }
//------------------
{ 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) { return a/b; } 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; } }
7,318,449
[ 1, 759, 1271, 413, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 7010, 565, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 377, 327, 374, 31, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 1815, 12, 71, 342, 279, 422, 324, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 7010, 565, 288, 203, 3639, 327, 279, 19, 70, 31, 203, 565, 289, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 7010, 565, 288, 203, 3639, 1815, 12, 70, 1648, 279, 1769, 203, 3639, 327, 279, 300, 324, 31, 203, 565, 289, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 7010, 565, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 1815, 12, 71, 1545, 279, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //pragma experimental ABIEncoderV2; import "./VcgBase.sol"; contract ExchangeVcgAuction is Ownable,Commission,ReentrancyGuardUpgradeable { using Strings for string; using Address for address; using SafeMath for uint256; enum State {Pending, Started, Ended, Cancelled} struct auctionInfo { address _nftContractAddress; uint256 _nftId; address _beneficiaryAddress; uint256 _initialPrice; uint256 _bidIncrement; uint256 _startTime; uint256 _stopTime; address highestBidder; mapping(address => uint256) fundsByBidder; State _state; uint256 _totalBalance; //bool isUsed; } mapping(uint256 => auctionInfo) private _auctionInfos; // Interface to halt all auctions. bool public IsHalted; // Admin withdrawal event WithDrawal(uint256 auctionid,address bidder,uint256 amount); // Pause and resume event Pause(); event Resume(); // New Bidding Event event NewBid(uint256 auctionid, uint256 price, address bidder); // Auction Finish Event event AuctionMade(uint256 auctionid, address oper ,State s); event AuctionAmountDetail(uint256 indexed auctionId, uint256 indexed beneficiaryReceived, uint256 indexed creatorReceived, uint256 platformReceived); // Halt transactions function halt() public onlyOwner { //require(_privilleged_operators[msg.sender] == true, "Operator only"); IsHalted = true; emit Pause(); } // Resume transactions function resume() public onlyOwner { IsHalted = false; emit Resume(); } modifier onlyAuctionExist(uint256 auctionID) { require(_auctionInfos[auctionID]._nftId != 0,"auctionID not existed..."); _; } modifier onlyOwnerOrBeneficiary(uint256 auctionID) { require(msg.sender == owner() || msg.sender == _auctionInfos[auctionID]._beneficiaryAddress, "only Owner Or Beneficiary allow to do this."); _; } modifier notBeneficiary(uint256 auctionID, address bider) { //if (bider == _auctionInfos[auctionid].beneficiaryAddress) throw; require(bider != _auctionInfos[auctionID]._beneficiaryAddress, "Bider Must not the beneficiary"); _; } modifier onlyAfterStart(uint256 auctionID) { require(block.timestamp > _auctionInfos[auctionID]._startTime, "only After Start"); _; } modifier onlyBeforeEnd(uint256 auctionID) { require(block.timestamp < _auctionInfos[auctionID]._stopTime, "only Before End"); _; } modifier onlyEndedOrCanceled(uint256 auctionID) { require(_auctionInfos[auctionID]._state == State.Ended || _auctionInfos[auctionID]._state == State.Cancelled, "The nft is still on auction, pls claim it or wait for finish"); _; } function hasRightToAuction(address nftContractaddr,uint256 tokenId) public view returns(bool) { return (IERC721(nftContractaddr).getApproved(tokenId) == address(this)); } function isTokenOwner(address nftContractaddr,address targetAddr, uint256 tokenId) internal view returns(bool) { return (targetAddr == IERC721(nftContractaddr).ownerOf(tokenId) ); } function isOnAuction(uint256 auctionID) public view returns(bool) { require(_auctionInfos[auctionID]._nftId != 0,"auctionID not existed..."); return (block.timestamp > _auctionInfos[auctionID]._startTime && block.timestamp < _auctionInfos[auctionID]._stopTime); } function createAuction(uint256 auctionID, address nftContractAddress, uint256 nftId, uint256 initialPrice, uint256 bidIncrement, uint256 startTime, uint256 stopTime) public { require(_auctionInfos[auctionID]._nftId == 0,"auctionID existed..."); require(!Address.isContract(msg.sender),"the sender should be a person, not a contract!"); require(startTime < stopTime, "stopTime must greater than startTime"); require(stopTime > block.timestamp + 600 , "stopTime must greater than current Time after 10 min"); require(isTokenOwner(nftContractAddress, msg.sender, nftId), "the sender isn't the owner of the token id nft!"); require(hasRightToAuction(nftContractAddress,nftId), "the exchange contracct is not the approved of the token."); require(initialPrice > 0 && initialPrice >= bidIncrement ,"need a vaild initial price"); auctionInfo storage ainfo = _auctionInfos[auctionID]; ainfo._nftContractAddress=nftContractAddress; ainfo._nftId=nftId; ainfo._beneficiaryAddress=msg.sender; ainfo._initialPrice=initialPrice; ainfo._bidIncrement=bidIncrement; ainfo._totalBalance = 0; ainfo._startTime=startTime; ainfo._stopTime=stopTime; ainfo._state=State.Pending; //ainfo.isUsed=true; emit AuctionMade(auctionID, address(this) ,State.Pending); } function getAuctionInfo(uint256 auctionID) external view returns (address,uint256,address,uint256,uint256, uint256,uint256,address,uint256,State,uint256){ auctionInfo storage info = _auctionInfos[auctionID]; return ( info._nftContractAddress, info._nftId, info._beneficiaryAddress, info._initialPrice, info._bidIncrement, info._startTime, info._stopTime, info.highestBidder, info.fundsByBidder[info.highestBidder], info._state, info._totalBalance ); } function clearAuctionInfo(uint256 auctionID) internal onlyAuctionExist(auctionID) { require(_auctionInfos[auctionID]._totalBalance == 0 , "only zero balance to be claered."); /* auctionInfo storage ainfo = _auctionInfos[auctionID]; ainfo._nftContractAddress=address(0); ainfo._nftId=0; ainfo._beneficiaryAddress=address(0); ainfo._initialPrice=0; ainfo._bidIncrement=0; ainfo._totalBalance = 0; ainfo._startTime=0; ainfo._stopTime=0; ainfo._state=State.Pending; ainfo.highestBidder=address(0); ainfo.isUsed=false; */ delete _auctionInfos[auctionID]; } function cancelAuction(uint256 auctionID) public onlyAuctionExist(auctionID) onlyOwnerOrBeneficiary(auctionID){ _auctionInfos[auctionID]._state = State.Cancelled; } function getHighestBid(uint256 auctionID) public view returns (address,uint256) { require(_auctionInfos[auctionID]._nftId != 0,"auctionID not existed..."); if(_auctionInfos[auctionID].highestBidder == address(0)) { return (address(0),0); } return (_auctionInfos[auctionID].highestBidder, _auctionInfos[auctionID].fundsByBidder[ _auctionInfos[auctionID].highestBidder]); } function placeBid(uint256 auctionID) public payable onlyAuctionExist(auctionID) notBeneficiary(auctionID,msg.sender) onlyAfterStart(auctionID) onlyBeforeEnd(auctionID) { // to place a bid auction should be running require(_auctionInfos[auctionID]._state == State.Pending || _auctionInfos[auctionID]._state == State.Started,"Invaild Auction State"); // minimum value allowed to be sent require(msg.value >= _auctionInfos[auctionID]._bidIncrement || _auctionInfos[auctionID]._bidIncrement == 0, "bid should be greater bid Increment"); uint256 currentBid = _auctionInfos[auctionID].fundsByBidder[msg.sender] + msg.value; // the currentBid should be greater than the highestBid. // Otherwise there's nothing to do. require((address(0) == _auctionInfos[auctionID].highestBidder && currentBid >= _auctionInfos[auctionID]._initialPrice)//first bid || (currentBid > _auctionInfos[auctionID].fundsByBidder[ _auctionInfos[auctionID].highestBidder]), "the currentBid should be greater than the highestBid."); //set state to started,when first vaild bid if (_auctionInfos[auctionID]._state == State.Pending) { _auctionInfos[auctionID]._state = State.Started; emit AuctionMade(auctionID, msg.sender ,State.Started); } // updating the mapping variable _auctionInfos[auctionID].fundsByBidder[msg.sender] = currentBid; _auctionInfos[auctionID]._totalBalance = _auctionInfos[auctionID]._totalBalance.add(msg.value); if (_auctionInfos[auctionID].highestBidder != msg.sender){ // highestBidder is another bidder _auctionInfos[auctionID].highestBidder = payable(msg.sender); } emit NewBid(auctionID, currentBid, msg.sender); } function finalizeAuction(uint256 auctionID) public // onlyAuctionExist(auctionID) onlyOwner nonReentrant { // support multi finalizeAuction call--2021.12.29 if (_auctionInfos[auctionID]._nftId == 0 || _auctionInfos[auctionID]._state == State.Ended) { return; } // the auction has been Cancelled or Ended require((_auctionInfos[auctionID]._state == State.Cancelled || _auctionInfos[auctionID]._state == State.Started || _auctionInfos[auctionID]._state == State.Pending) && block.timestamp > _auctionInfos[auctionID]._stopTime, "the auction may be Cancelled or Ended"); if(_auctionInfos[auctionID]._state == State.Started) { address payable recipient; uint256 value; recipient = payable(_auctionInfos[auctionID]._beneficiaryAddress); value = _auctionInfos[auctionID].fundsByBidder[ _auctionInfos[auctionID].highestBidder]; // resetting the bids of the recipient to avoid multiple transfers to the same recipient _auctionInfos[auctionID].fundsByBidder[ _auctionInfos[auctionID].highestBidder] = 0; _auctionInfos[auctionID]._totalBalance = _auctionInfos[auctionID]._totalBalance.sub(value); // IERC721(_auctionInfos[auctionID]._nftContractAddress).safeTransferFrom( _auctionInfos[auctionID]._beneficiaryAddress, _auctionInfos[auctionID].highestBidder, _auctionInfos[auctionID]._nftId ); (address creator,uint256 royalty) = IVcgERC721TokenWithRoyalty(_auctionInfos[auctionID]._nftContractAddress).royaltyInfo(_auctionInfos[auctionID]._nftId,value); (address platform,uint256 fee) = calculateFee(value); require(value > royalty + fee,"No enough Amount to pay except royalty and platform service fee"); if(creator != address(0) && royalty >0 && royalty < value) { payable(creator).transfer(royalty); value = value.sub(royalty); } if(fee > 0 && fee < value) { //payable(platform).transfer(fee); //(bool sent, bytes memory data) = platform.call{value: fee}(""); //require(sent, "Failed to send Ether to platform"); Address.sendValue(payable(platform),fee); value = value.sub(fee); } //sends value to the recipient recipient.transfer(value); emit AuctionAmountDetail(auctionID,value,royalty,fee); } _auctionInfos[auctionID]._state = State.Ended; emit AuctionMade(auctionID, msg.sender ,State.Ended); if(_auctionInfos[auctionID]._totalBalance == 0){ clearAuctionInfo(auctionID); } } function withdraw(uint256 auctionID) public onlyAuctionExist(auctionID) onlyEndedOrCanceled(auctionID) returns (bool success) { address payable withdrawalAccount; uint withdrawalAmount; if (_auctionInfos[auctionID]._state == State.Cancelled) { // if the auction was canceled, everyone should simply be allowed to withdraw their funds withdrawalAccount = payable(msg.sender); withdrawalAmount = _auctionInfos[auctionID].fundsByBidder[withdrawalAccount]; } else { require(msg.sender != _auctionInfos[auctionID].highestBidder , "highestBidder does not allow to withdraw."); // anyone who participated but did not win the auction should be allowed to withdraw // the full amount of their funds withdrawalAccount = payable(msg.sender); withdrawalAmount = _auctionInfos[auctionID].fundsByBidder[withdrawalAccount]; } if (withdrawalAmount == 0) { revert(); } delete _auctionInfos[auctionID].fundsByBidder[withdrawalAccount]; /* _auctionInfos[auctionID].fundsByBidder[withdrawalAccount] = _auctionInfos[auctionID].fundsByBidder[withdrawalAccount].sub(withdrawalAmount); */ // send the funds if (!withdrawalAccount.send(withdrawalAmount)){ revert(); } _auctionInfos[auctionID]._totalBalance = _auctionInfos[auctionID]._totalBalance.sub(withdrawalAmount); if(_auctionInfos[auctionID]._totalBalance == 0){ clearAuctionInfo(auctionID); } emit WithDrawal(auctionID,withdrawalAccount,withdrawalAmount); return true; } function getBalance(uint256 auctionID,address target) public view onlyAuctionExist(auctionID) returns (uint256) { if(address(0) == target){ return _auctionInfos[auctionID].fundsByBidder[msg.sender]; } return _auctionInfos[auctionID].fundsByBidder[target]; } function destroyContract() external onlyOwner { selfdestruct(payable(owner())); } }
Resume transactions
function resume() public onlyOwner { IsHalted = false; emit Resume(); }
1,185,407
[ 1, 20911, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10774, 1435, 1071, 1338, 5541, 288, 203, 3639, 2585, 44, 287, 2344, 273, 629, 31, 203, 3639, 3626, 1124, 2066, 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 ]
./full_match/1/0xe1272adbf95FA29ab6aC9Cd8bF2D5462BCD766B3/sources/contracts/cash/CashManager.sol
* @notice Sets mint exchange rate @param exchangeRate New mint exchange rate (in 18 decimals) @param epochToSet The epoch we want to set the exchange rate for @dev If the exchange rate differs more than `exchangeRateDeltaLimit` from the last exchange rate set, the entire contract will be paused. See `overrideExchangeRate` should this check need to be bypassed/
function setMintExchangeRate( uint256 exchangeRate, uint256 epochToSet ) external override updateEpoch onlyRole(SETTER_ADMIN) { if (exchangeRate == 0) { revert ZeroExchangeRate(); } if (epochToSet >= currentEpoch) { revert EpochNotElapsed(); } if (epochToExchangeRate[epochToSet] != 0) { revert EpochExchangeRateAlreadySet(); } uint256 rateDifference; if (exchangeRate > lastSetMintExchangeRate) { rateDifference = exchangeRate - lastSetMintExchangeRate; rateDifference = lastSetMintExchangeRate - exchangeRate; } uint256 maxDifferenceThisEpoch = (lastSetMintExchangeRate * exchangeRateDeltaLimit) / BPS_DENOMINATOR; if (rateDifference > maxDifferenceThisEpoch) { epochToExchangeRate[epochToSet] = exchangeRate; _pause(); emit MintExchangeRateCheckFailed( epochToSet, lastSetMintExchangeRate, exchangeRate ); uint256 oldExchangeRate = lastSetMintExchangeRate; epochToExchangeRate[epochToSet] = exchangeRate; lastSetMintExchangeRate = exchangeRate; emit MintExchangeRateSet(epochToSet, oldExchangeRate, exchangeRate); } }
17,003,311
[ 1, 2785, 312, 474, 7829, 4993, 225, 7829, 4727, 1166, 312, 474, 7829, 4993, 261, 267, 6549, 15105, 13, 225, 7632, 25208, 282, 1021, 7632, 732, 2545, 358, 444, 326, 7829, 4993, 364, 225, 971, 326, 7829, 4993, 21944, 1898, 2353, 1375, 16641, 4727, 9242, 3039, 68, 1377, 628, 326, 1142, 7829, 4993, 444, 16, 326, 7278, 6835, 903, 506, 17781, 18, 1377, 2164, 1375, 10601, 11688, 4727, 68, 1410, 333, 866, 1608, 358, 506, 635, 23603, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 15430, 474, 11688, 4727, 12, 203, 565, 2254, 5034, 7829, 4727, 16, 203, 565, 2254, 5034, 7632, 25208, 203, 225, 262, 3903, 3849, 1089, 14638, 1338, 2996, 12, 1090, 11976, 67, 15468, 13, 288, 203, 565, 309, 261, 16641, 4727, 422, 374, 13, 288, 203, 1377, 15226, 12744, 11688, 4727, 5621, 203, 565, 289, 203, 565, 309, 261, 12015, 25208, 1545, 783, 14638, 13, 288, 203, 1377, 15226, 512, 6127, 1248, 28827, 5621, 203, 565, 289, 203, 565, 309, 261, 12015, 774, 11688, 4727, 63, 12015, 25208, 65, 480, 374, 13, 288, 203, 1377, 15226, 512, 6127, 11688, 4727, 9430, 694, 5621, 203, 565, 289, 203, 203, 565, 2254, 5034, 4993, 16220, 31, 203, 565, 309, 261, 16641, 4727, 405, 1142, 694, 49, 474, 11688, 4727, 13, 288, 203, 1377, 4993, 16220, 273, 7829, 4727, 300, 1142, 694, 49, 474, 11688, 4727, 31, 203, 1377, 4993, 16220, 273, 1142, 694, 49, 474, 11688, 4727, 300, 7829, 4727, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 943, 16220, 2503, 14638, 273, 261, 2722, 694, 49, 474, 11688, 4727, 380, 203, 1377, 7829, 4727, 9242, 3039, 13, 342, 605, 5857, 67, 13296, 1872, 706, 3575, 31, 203, 203, 565, 309, 261, 5141, 16220, 405, 943, 16220, 2503, 14638, 13, 288, 203, 1377, 7632, 774, 11688, 4727, 63, 12015, 25208, 65, 273, 7829, 4727, 31, 203, 1377, 389, 19476, 5621, 203, 1377, 3626, 490, 474, 11688, 4727, 1564, 2925, 12, 203, 3639, 7632, 25208, 16, 203, 3639, 1142, 694, 49, 474, 11688, 4727, 16, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.2; import "./HedgerParty.sol"; import "./SafeMath.sol"; contract OpenHedge1200 { // OpenHedgeProtocol Version string public constant OpenHedgeProtocol = "0.12.0"; enum HedgeStatus {AVAILABLE, RESERVED, FUNDED, CANCELLED, ACTIVE, FINISHED} HedgeStatus public status = HedgeStatus.AVAILABLE; // Owner address address private ownerAddr; // Timestamp contract deployed On uint256 private deployedOn; // Seller (Party A) Object HedgerParty private seller; // Buyer (Party B) Object HedgerParty private buyer; // Maturity of contract in seconds int256 public maturity; // Premium/Fee paid to Buyer uint16 private premium; // Premium/Fee amount uint256 private premiumAmount; // Timestamp this contract became reserved for Party A uint256 private reservedOn; // Timestamp contract HedgeStatus is ACTIVE uint256 private activatedOn; // Timestamp contract HedgeStatus is FINISHED uint256 private finishedOn; event Spend(address asset, address payee, uint256 amount); // For certain methods that are only callable by ProSwap owner address modifier onlyOwner { if (msg.sender != ownerAddr) { revert("Can only be called by Owner address"); } _; } // For certain methods that are only callable by Seller address modifier onlySeller { if (msg.sender != seller.account()) { revert("Can only be called by Seller address"); } _; } modifier onlyOwnerOrSeller { if (msg.sender != ownerAddr) { if (msg.sender != seller.account()) { revert("Can only be called by Admin or Seller address"); } } _; } // Todo: add ownership transfer // Open Hedger Constructor constructor() { ownerAddr = msg.sender; deployedOn = block.timestamp; seller = new HedgerParty(address(this)); buyer = new HedgerParty(address(this)); } // Get owner address function ownerAddress() public view returns (address) { return (ownerAddr); } // Determines if OH-SC can be reset at current stage function canReset() public view returns (bool) { if (status == HedgeStatus.RESERVED) {// Available SC was allotted but not yet funded return true; } if (status == HedgeStatus.CANCELLED) {// SC was allotted, funded and then later cancelled return true; } if (status == HedgeStatus.FINISHED) {// SC was finished successfully return true; } return false; } // Super reset function reset() public onlyOwner { if (!canReset()) { revert("Hedger cannot be reset"); } status = HedgeStatus.AVAILABLE; seller.reset(); buyer.reset(); maturity = 0; premium = 0; premiumAmount = 0; reservedOn = 0; activatedOn = 0; finishedOn = 0; uint256 eth = address(this).balance; if (eth > 0) { spend(address(0), ownerAddr, eth); } } // Reserve this AVAILABLE hedge contract function reserve(address _userA, address _assetA, uint256 _assetAAmount, address _assetB, uint256 _assetBAmount, int256 _maturity, uint16 _premium) public onlyOwner { if (status != HedgeStatus.AVAILABLE) { revert("HedgerStatus is not AVAILABLE"); } status = HedgeStatus.RESERVED; seller.reserve(_assetA, _assetAAmount); seller.setUserAccount(_userA); buyer.reserve(_assetB, _assetBAmount); maturity = _maturity; premium = _premium; premiumAmount = SafeMath.div(SafeMath.mul(premium, _assetAAmount), 10000); reservedOn = block.timestamp; } // Get the premium amount function getPremium() public view returns (uint16, uint256) { return ( premium, premiumAmount ); } // Get current timestamp as per last block function currentTs() public view returns (int256) { return int256(block.timestamp); } // Get number of seconds since contract is HedgeStatus.ACTIVE function activatedSince() public view returns (int256) { if (activatedOn > 0) { return int256(block.timestamp) - int256(activatedOn); } return 0; } // Check if contract has matured function isMatured() public view returns (bool) { if (maturity > 0) { int256 matured = int256(activatedSince()) - int256(maturity); if (matured > 0) { return true; } } return false; } // Check if funds are claimable function isClaimable() public view returns (bool) { return status == HedgeStatus.ACTIVE && isMatured(); } // Get seller information function getPartyA() public view returns (uint8, string memory, address, uint256, address, string memory, uint8, uint256) { return ( uint8(seller.status()), seller.getStatusStr(), seller.account(), seller.getBalance(), seller.assetAddr(), seller.assetCode(), seller.assetScale(), seller.amount() ); } // Get buyer information function getPartyB() public view returns (uint8, string memory, address, uint256, address, string memory, uint8, uint256) { return ( uint8(buyer.status()), buyer.getStatusStr(), buyer.account(), buyer.getBalance(), buyer.assetAddr(), buyer.assetCode(), buyer.assetScale(), buyer.amount() ); } // Spend ETH or ERC20 to payee function spend(address _asset, address _payee, uint256 _amount) internal { emit Spend(_asset, _payee, _amount); if (_asset == address(0)) { (bool success,) = _payee.call{value : _amount}(""); require(success); } else { ERC20(_asset).transfer(_payee, _amount); } } // Checks if hedge can be funded function canBeFunded() public view { if (status != HedgeStatus.RESERVED) { revert("Hedge status cannot be funded"); } if (seller.isFunded()) { revert("Hedge already marked funded"); } } // Mark hedge as funded function _markAsFunded() internal { status = HedgeStatus.FUNDED; seller.markAsFunded(); } // Handling incoming ETH receive() external payable { // Check if can be funded canBeFunded(); // Further checks if (msg.sender != seller.account()) { revert("Only seller can fund contract with ETH"); } if (seller.assetAddr() != address(0)) { revert("Cannot fund contract with ETH"); } uint256 amtReq = SafeMath.add(seller.amount(), premiumAmount); uint256 ethBalance = address(this).balance; if (ethBalance >= amtReq) { uint256 leftover = ethBalance - amtReq; if (leftover > 0) { spend(address(0), seller.account(), leftover); } _markAsFunded(); } } // Fund the hedge with ERC20 function fundErc20() public onlyOwnerOrSeller returns (bool) { // Check if can be funded canBeFunded(); if (seller.assetAddr() == address(0)) {// Selling ERC20? revert("Cannot fund contract with ERC20"); } if (seller.account() == address(0)) { revert("Seller account not set"); } uint256 amtReq = SafeMath.add(seller.amount(), premiumAmount); ERC20 sellerToken = ERC20(seller.assetAddr()); // Check ERC20 allowance (uint256 allowance) = sellerToken.allowance(seller.account(), address(this)); if (allowance < amtReq) { revert("Not enough ERC20 allowance"); } (uint balance) = sellerToken.balanceOf(seller.account()); if (balance < amtReq) { revert("Not enough ERC20 balance"); } sellerToken.transferFrom(seller.account(), address(this), amtReq); // Verify transfer from ERC20 (uint newTokenBalance) = sellerToken.balanceOf(address(this)); if (newTokenBalance < amtReq) { revert("Not receive full ERC20"); } _markAsFunded(); return true; } // Cancel funded, but unsold hedge back to seller's address function cancel() public onlyOwnerOrSeller { if (status != HedgeStatus.FUNDED || !seller.isFunded()) { revert("Cannot cancel hedge at current stage"); } // Send back all held assets to seller uint256 balance = seller.getBalance(); spend(seller.assetAddr(), seller.account(), balance); // Set status to cancelled status = HedgeStatus.CANCELLED; seller.markWithdrawn(); } // Buy the hedge function buyHedge(address _user) public onlyOwner { if (buyer.account() != address(0) || buyer.isFunded()) {// Checking if its still up for sale revert("Hedge no longer available"); } if (status != HedgeStatus.FUNDED || !seller.isFunded()) { revert("Cannot buy unfunded hedge"); } // Check ERC20 allowance ERC20 token = ERC20(buyer.assetAddr()); (uint256 allowance) = token.allowance(_user, address(this)); if (allowance < buyer.amount()) { revert("Not enough ERC20 allowance"); } (uint balance) = token.balanceOf(_user); if (balance < buyer.amount()) { revert("Not enough ERC20 balance"); } // Transfer ERC20 units to itself token.transferFrom(_user, address(this), buyer.amount()); // Verify transfer from ERC20 (uint ownTokenBalance) = token.balanceOf(address(this)); if (ownTokenBalance < buyer.amount()) { revert("Not receive full ERC20"); } // Mark Buyer Hedge Object buyer.setUserAccount(_user); buyer.markAsFunded(); // Transfer premium to Buyer spend(seller.assetAddr(), _user, premiumAmount); // Activate Hedge status = HedgeStatus.ACTIVE; activatedOn = block.timestamp; } // Claim hedge function claim(uint8 _for, uint8 _asset) public returns (bool) { if (status != HedgeStatus.ACTIVE) {// Status check revert("Hedge cannot be claimed at this stage"); } if (maturity > activatedSince()) {// Check maturity revert("Hedge not matured"); } if (msg.sender != ownerAddr) { if (msg.sender == seller.account()) { _for = 1; } else if (msg.sender == buyer.account()) { _for = 2; } else { revert("Unauthorized address"); } } // Accounting bool claimed = false; if (_for == 1) {// On behalf of Party A if (_asset != 1 && _asset != 2) {// Check asset claim revert("Invalid seller asset claim"); } if (_asset == 1) { // Return asset A to seller spend(seller.assetAddr(), seller.account(), seller.amount()); // Return asset B to buyer spend(buyer.assetAddr(), buyer.account(), buyer.amount()); } else if (_asset == 2) { // Return asset B to seller spend(buyer.assetAddr(), seller.account(), buyer.amount()); // Return asset A to buyer spend(seller.assetAddr(), buyer.account(), seller.amount()); } } else if (_for == 2) {// On behalf of Party B // Return asset A to seller spend(seller.assetAddr(), seller.account(), seller.amount()); // Return asset B to buyer spend(buyer.assetAddr(), buyer.account(), buyer.amount()); } else { revert("Invalid argument _for"); } // Change Statuses status = HedgeStatus.FINISHED; finishedOn = block.timestamp; seller.markWithdrawn(); buyer.markWithdrawn(); return claimed; } // Refuse any incoming ETH value with calls fallback() external payable { revert("Do not send ETH with your call"); } }
OpenHedgeProtocol Version Owner address Timestamp contract deployed On Seller (Party A) Object Buyer (Party B) Object Maturity of contract in seconds Premium/Fee paid to Buyer Premium/Fee amount Timestamp this contract became reserved for Party A Timestamp contract HedgeStatus is ACTIVE Timestamp contract HedgeStatus is FINISHED For certain methods that are only callable by ProSwap owner address
{ string public constant OpenHedgeProtocol = "0.12.0"; HedgeStatus public status = HedgeStatus.AVAILABLE; address private ownerAddr; uint256 private deployedOn; HedgerParty private seller; HedgerParty private buyer; int256 public maturity; uint16 private premium; uint256 private premiumAmount; uint256 private reservedOn; uint256 private activatedOn; uint256 private finishedOn; event Spend(address asset, address payee, uint256 amount); enum HedgeStatus {AVAILABLE, RESERVED, FUNDED, CANCELLED, ACTIVE, FINISHED} modifier onlyOwner { if (msg.sender != ownerAddr) { revert("Can only be called by Owner address"); } _; } modifier onlyOwner { if (msg.sender != ownerAddr) { revert("Can only be called by Owner address"); } _; } modifier onlySeller { if (msg.sender != seller.account()) { revert("Can only be called by Seller address"); } _; } modifier onlySeller { if (msg.sender != seller.account()) { revert("Can only be called by Seller address"); } _; } modifier onlyOwnerOrSeller { if (msg.sender != ownerAddr) { if (msg.sender != seller.account()) { revert("Can only be called by Admin or Seller address"); } } _; } modifier onlyOwnerOrSeller { if (msg.sender != ownerAddr) { if (msg.sender != seller.account()) { revert("Can only be called by Admin or Seller address"); } } _; } modifier onlyOwnerOrSeller { if (msg.sender != ownerAddr) { if (msg.sender != seller.account()) { revert("Can only be called by Admin or Seller address"); } } _; } constructor() { ownerAddr = msg.sender; deployedOn = block.timestamp; seller = new HedgerParty(address(this)); buyer = new HedgerParty(address(this)); } function ownerAddress() public view returns (address) { return (ownerAddr); } function canReset() public view returns (bool) { return true; } return true; }
1,085,504
[ 1, 3678, 44, 7126, 5752, 4049, 16837, 1758, 8159, 6835, 19357, 2755, 4352, 749, 261, 17619, 432, 13, 1033, 605, 16213, 261, 17619, 605, 13, 1033, 14493, 2336, 434, 6835, 316, 3974, 453, 2764, 5077, 19, 14667, 30591, 358, 605, 16213, 453, 2764, 5077, 19, 14667, 3844, 8159, 333, 6835, 506, 71, 339, 8735, 364, 6393, 93, 432, 8159, 6835, 670, 7126, 1482, 353, 21135, 8159, 6835, 670, 7126, 1482, 353, 25768, 2056, 2457, 8626, 2590, 716, 854, 1338, 4140, 635, 1186, 12521, 3410, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 95, 203, 565, 533, 1071, 5381, 3502, 44, 7126, 5752, 273, 315, 20, 18, 2138, 18, 20, 14432, 203, 203, 565, 670, 7126, 1482, 1071, 1267, 273, 670, 7126, 1482, 18, 23222, 31, 203, 203, 565, 1758, 3238, 3410, 3178, 31, 203, 565, 2254, 5034, 3238, 19357, 1398, 31, 203, 203, 565, 670, 329, 693, 17619, 3238, 29804, 31, 203, 565, 670, 329, 693, 17619, 3238, 27037, 31, 203, 565, 509, 5034, 1071, 29663, 31, 203, 565, 2254, 2313, 3238, 23020, 5077, 31, 203, 565, 2254, 5034, 3238, 23020, 5077, 6275, 31, 203, 565, 2254, 5034, 3238, 8735, 1398, 31, 203, 565, 2254, 5034, 3238, 14892, 1398, 31, 203, 565, 2254, 5034, 3238, 6708, 1398, 31, 203, 203, 565, 871, 348, 1302, 12, 2867, 3310, 16, 1758, 8843, 1340, 16, 2254, 5034, 3844, 1769, 203, 203, 203, 565, 2792, 670, 7126, 1482, 288, 23222, 16, 2438, 19501, 16, 478, 2124, 7660, 16, 29641, 6687, 16, 21135, 16, 25768, 2056, 97, 203, 565, 9606, 1338, 5541, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 3178, 13, 288, 203, 5411, 15226, 2932, 2568, 1338, 506, 2566, 635, 16837, 1758, 8863, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 3178, 13, 288, 203, 5411, 15226, 2932, 2568, 1338, 506, 2566, 635, 16837, 1758, 8863, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 22050, 288, 203, 3639, 309, 261, 3576, 18, 2 ]
./full_match/1/0xFb4DE84c4375d7c8577327153dE88f58F69EeC81/sources/contracts/registries/PoolRegistry.sol
@inheritdoc IPoolRegistry
function getUnderlyingTokens(address poolAddress) external view override hasMatchingPool(poolAddress) returns (IERC20[] memory underlyingTokens) { return pools[poolsIndexOfPlusOne[poolAddress] - 1].underlyingTokens; }
4,822,814
[ 1, 36, 10093, 467, 2864, 4243, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10833, 765, 6291, 5157, 12, 2867, 2845, 1887, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 711, 9517, 2864, 12, 6011, 1887, 13, 203, 3639, 1135, 261, 45, 654, 39, 3462, 8526, 3778, 6808, 5157, 13, 203, 565, 288, 203, 3639, 327, 16000, 63, 27663, 31985, 13207, 3335, 63, 6011, 1887, 65, 300, 404, 8009, 9341, 6291, 5157, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts-upgradeable/presets/ERC721PresetMinterPauserAutoIdUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {NativeMetaTransaction} from "./NativeMetaTransaction.sol"; import {ContextMixin} from "./ContextMixin.sol"; //import { SoapPunkCollectiblesChild } from "./SoupPunk_child.sol"; contract SpaceTime is ERC721PresetMinterPauserAutoIdUpgradeable, NativeMetaTransaction, ContextMixin { using SafeMathUpgradeable for uint256; uint256 private _tokenCount; uint256 private _endTime; // uint256 private _multPrice; uint256 private _refundByCatch; // uint8 private _maxVotes; uint8 private _maxMintByAccount; // uint16 private _totalArtworkAmount; uint32 private _totalTokenAmount; // string private _contractURI; SoapPunkCollectiblesChild private _spContract; // Mapping from address to vote count mapping (address => uint8) private _accountVoteCount; // Mapping from address to amount of mints mapping (address => uint8) private _accountMintCount; // Mapping from token id to minter mapping (uint256 => address) private _artworkMinterAccount; // Mapping from token id to boolean -> true if arwork is minted mapping (uint256 => bool) private _artworkMinted; // Mapping from address to votes array mapping (address => uint256[10]) private _accountVoteArtwork; // Mapping from address to boolean -> true if refund was used mapping (address => bool) private _accountRefundUsed; IERC20 private _tokenERC20; function initialize(string memory name, string memory symbol, string memory baseURI, string memory domainSeparator) initializer public { __ERC721PresetMinterPauserAutoId_init(name, symbol, baseURI); _initializeEIP712(domainSeparator); _tokenCount = 0; uint256 _startTime = block.timestamp; setEndTime(_startTime.add(2592000)); setPrice(5000000000000000000); // 5 Matic setContractURI("ipfs://contract-metadata"); } /** * @dev the URL to a JSON file with contract metadata for OpenSea. */ function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Returns the address of the current owner, OpenSea uses this information. */ function owner() public view returns (address) { return getRoleMember(DEFAULT_ADMIN_ROLE, 0); } /** * @dev Returns information about the fees for a given token. */ function royaltyInfo(uint256 _tokenId, uint256 _value) external view override returns (address receiver, uint256 amount) { return (address(this), _value.div(100); } function setERC20(IERC20 token) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to set token"); _tokenERC20 = token; } function setBaseURI(string memory baseURI, uint256 id) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to change uri"); _setBaseURI(baseURI); } function setContractURI(string memory __contractURI) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to change contract uri"); _contractURI = __contractURI; ContractURISet(__contractURI); } function setPrice(uint256 multPrice) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to set price"); _multPrice = multPrice; emit PriceSet(multPrice); } function setEndTime(uint256 endTime) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to change end time"); _endTime = endTime; emit EndTimeSet(endTime); } function mint(address to) public override { require(false, "SpaceTime: mint is not allowed"); // Nobody can call mint() } function getPrice(address for_account) public view returns(uint256 price, bool use_refund) { // bool willUseRefund = false; // If user didn't used the refund if (!_accountRefundUsed[for_account]) { // Check if owns Soaps if (_spContract.balanceOf(for_account, 0)>0) { willUseRefund = true; } else { // Iterate over votes for (uint i=0; i<_accountVoteCount[for_account]; i++) { if (_artworkMinterAccount[_accountVoteArtwork[for_account][i]] == for_account) { continue; } // If the voted artwork was minted if (_artworkMinted[_accountVoteArtwork[for_account][i]]) { willUseRefund = true; break; } } } } // uint256 tmpPrice = _multPrice.mul(5000); if (_tokenCount < 400) { tmpPrice = _multPrice.mul(10); } else if (_tokenCount < 800) { tmpPrice = _multPrice.mul(25); } else if (_tokenCount < 950) { tmpPrice = _multPrice.mul(45); } else if (_tokenCount < 990) { tmpPrice = _multPrice.mul(85); } else if (_tokenCount < 1024) { tmpPrice = _multPrice.mul(150); } if (!willUseRefund) { // Price not cut in half tmpPrice = tmpPrice.mul(2); } // return (tmpPrice, willUseRefund); } /** * @dev Get price, setting the refund as used. */ function _getPrice() private returns(uint256 price) { (uint256 tmpPrice, bool willUseRefund) = getPrice(_msgSender()); // Mark refund as used if (willUseRefund) { _accountRefundUsed[_msgSender()] = true; } return tmpPrice; } /** * @dev Mints artwork on sale. */ function buy() external //payable price(_getPrice()) returns(uint256 index) { require(!paused(), "SpaceTime: token mint while paused"); _tokenCount = _tokenCount.add(1); _artworkMinterAccount[id] = _msgSender(); _artworkMinted[id] = true; _accountMintCount[_msgSender()] += 1; _mint(_msgSender(), _tokenCount-1); return _tokenCount-1; } /* * @dev Remove all Ether from the contract, and transfer it to account of owner */ function withdrawBalance() external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to withdraw"); uint256 balance = _tokenERC20.balanceOf(address(this)); _tokenERC20.transfer(_msgSender(), balance); emit Withdraw(balance); } // Modifiers /** * @dev modifier Associete fee with a function call. If the caller sent too much, then is refunded, but only after the function body. * This was dangerous before Solidity version 0.4.0, where it was possible to skip the part after `_;`. * @param _amount - ether needed to call the function */ modifier price(uint256 _amount) { require(_tokenERC20.balanceOf(_msgSender()) >= _amount, "SpaceTime: Not enough ERC20 tokens."); require(_tokenERC20.allowance(_msgSender(), address(this)) >= _amount, "SpaceTime: Not enough ERC20 token allowance."); _; _tokenERC20.transferFrom(_msgSender(), address(this), _amount); } // Events /** * @dev Emits when owner take ETH out of contract * @param balance - amount of ETh sent out from contract */ event Withdraw(uint256 balance); /** * @dev Emits when a new price is set * @param multPrice - a multiplier for the price */ event PriceSet(uint256 multPrice); /** * @dev Emits when an artwork is voted * @param id - an artwork id * @param account - an account address */ event Vote(uint256 id, address account); /** * @dev Emits when the SoapPunk contract address is set * @param spAddress - an address */ event SPAddressSet(address spAddress); /** * @dev Emits when the contract URI is set * @param contractURI - an URL to the metadata */ event ContractURISet(string contractURI); /** * @dev Emits when the end time is set * @param endTime - the event end time */ event EndTimeSet(uint256 endTime); // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } }
* @dev Emits when the end time is set @param endTime - the event end time/
event EndTimeSet(uint256 endTime);
2,564,417
[ 1, 1514, 1282, 1347, 326, 679, 813, 353, 444, 225, 13859, 300, 326, 871, 679, 813, 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, 871, 4403, 950, 694, 12, 11890, 5034, 13859, 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 ]
// 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/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IVeANGLE.sol"; import "./interfaces/IFeeDistributor.sol"; import "./interfaces/IAngleGaugeController.sol"; /// @title AngleLocker /// @author StakeDAO /// @notice Locks the ANGLE tokens to veANGLE contract contract AngleLocker { using SafeERC20 for IERC20; using Address for address; /* ========== STATE VARIABLES ========== */ address public governance; address public angleDepositor; address public accumulator; address public constant angle = address(0x31429d1856aD1377A8A0079410B297e1a9e214c2); address public constant veAngle = address(0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5); address public feeDistributor = address(0x7F82ff050128e29Fd89D85d01b93246F744E62A0); address public gaugeController = address(0x9aD7e7b0877582E14c17702EecF49018DD6f2367); /* ========== EVENTS ========== */ event LockCreated(address indexed user, uint256 value, uint256 duration); event TokenClaimed(address indexed user, uint256 value); event Voted(uint256 _voteId, address indexed _votingAddress, bool _support); event VotedOnGaugeWeight(address indexed _gauge, uint256 _weight); event Released(address indexed user, uint256 value); event GovernanceChanged(address indexed newGovernance); event AngleDepositorChanged(address indexed newAngleDepositor); event AccumulatorChanged(address indexed newAccumulator); event FeeDistributorChanged(address indexed newFeeDistributor); event GaugeControllerChanged(address indexed newGaugeController); /* ========== CONSTRUCTOR ========== */ constructor(address _accumulator) { governance = msg.sender; accumulator = _accumulator; IERC20(angle).approve(veAngle, type(uint256).max); } /* ========== MODIFIERS ========== */ modifier onlyGovernance() { require(msg.sender == governance, "!gov"); _; } modifier onlyGovernanceOrAcc() { require(msg.sender == governance || msg.sender == accumulator, "!(gov||acc)"); _; } modifier onlyGovernanceOrDepositor() { require(msg.sender == governance || msg.sender == angleDepositor, "!(gov||proxy||AngleDepositor)"); _; } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Creates a lock by locking ANGLE token in the veAngle contract for the specified time /// @dev Can only be called by governance or proxy /// @param _value The amount of token to be locked /// @param _unlockTime The duration for which the token is to be locked function createLock(uint256 _value, uint256 _unlockTime) external onlyGovernanceOrDepositor { IVeANGLE(veAngle).create_lock(_value, _unlockTime); emit LockCreated(msg.sender, _value, _unlockTime); } /// @notice Increases the amount of ANGLE locked in veANGLE /// @dev The ANGLE needs to be transferred to this contract before calling /// @param _value The amount by which the lock amount is to be increased function increaseAmount(uint256 _value) external onlyGovernanceOrDepositor { IVeANGLE(veAngle).increase_amount(_value); } /// @notice Increases the duration for which ANGLE is locked in veANGLE for the user calling the function /// @param _unlockTime The duration in seconds for which the token is to be locked function increaseUnlockTime(uint256 _unlockTime) external onlyGovernanceOrDepositor { IVeANGLE(veAngle).increase_unlock_time(_unlockTime); } /// @notice Claim the token reward from the ANGLE fee Distributor passing the token as input parameter /// @param _recipient The address which will receive the claimed token reward function claimRewards(address _token, address _recipient) external onlyGovernanceOrAcc { uint256 claimed = IFeeDistributor(feeDistributor).claim(); emit TokenClaimed(_recipient, claimed); IERC20(_token).safeTransfer(_recipient, claimed); } /// @notice Withdraw the ANGLE from veANGLE /// @dev call only after lock time expires /// @param _recipient The address which will receive the released ANGLE function release(address _recipient) external onlyGovernanceOrDepositor { IVeANGLE(veAngle).withdraw(); uint256 balance = IERC20(angle).balanceOf(address(this)); IERC20(angle).safeTransfer(_recipient, balance); emit Released(_recipient, balance); } /// @notice Vote on Angle Gauge Controller for a gauge with a given weight /// @param _gauge The gauge address to vote for /// @param _weight The weight with which to vote function voteGaugeWeight(address _gauge, uint256 _weight) external onlyGovernance { IAngleGaugeController(gaugeController).vote_for_gauge_weights(_gauge, _weight); emit VotedOnGaugeWeight(_gauge, _weight); } function setGovernance(address _governance) external onlyGovernance { governance = _governance; emit GovernanceChanged(_governance); } function setAngleDepositor(address _angleDepositor) external onlyGovernance { angleDepositor = _angleDepositor; emit AngleDepositorChanged(_angleDepositor); } function setFeeDistributor(address _newYD) external onlyGovernance { feeDistributor = _newYD; emit FeeDistributorChanged(_newYD); } function setGaugeController(address _gaugeController) external onlyGovernance { gaugeController = _gaugeController; emit GaugeControllerChanged(_gaugeController); } function setAccumulator(address _accumulator) external onlyGovernance { accumulator = _accumulator; emit AccumulatorChanged(_accumulator); } /// @notice execute a function /// @param to Address to sent the value to /// @param value Value to be sent /// @param data Call function data function execute( address to, uint256 value, bytes calldata data ) external onlyGovernanceOrDepositor returns (bool, bytes memory) { (bool success, bytes memory result) = to.call{ value: value }(data); return (success, result); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IAngleGaugeController { function vote_for_gauge_weights(address, uint256) external; function vote( uint256, bool, bool ) external; //voteId, support, executeIfDecided } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IFeeDistributor { function claim() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IVeANGLE { struct LockedBalance { int128 amount; uint256 end; } function create_lock(uint256 _value, uint256 _unlock_time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; }
========== MUTATIVE FUNCTIONS ========== */ @notice Creates a lock by locking ANGLE token in the veAngle contract for the specified time @dev Can only be called by governance or proxy @param _value The amount of token to be locked @param _unlockTime The duration for which the token is to be locked
function createLock(uint256 _value, uint256 _unlockTime) external onlyGovernanceOrDepositor { IVeANGLE(veAngle).create_lock(_value, _unlockTime); emit LockCreated(msg.sender, _value, _unlockTime); }
14,538,777
[ 1, 1432, 631, 490, 1693, 12992, 13690, 55, 422, 1432, 342, 225, 10210, 279, 2176, 635, 18887, 432, 4960, 900, 1147, 316, 326, 10489, 8467, 6835, 364, 326, 1269, 813, 225, 4480, 1338, 506, 2566, 635, 314, 1643, 82, 1359, 578, 2889, 225, 389, 1132, 1021, 3844, 434, 1147, 358, 506, 8586, 225, 389, 26226, 950, 1021, 3734, 364, 1492, 326, 1147, 353, 358, 506, 8586, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 752, 2531, 12, 11890, 5034, 389, 1132, 16, 2254, 5034, 389, 26226, 950, 13, 3903, 1338, 43, 1643, 82, 1359, 1162, 758, 1724, 280, 288, 203, 202, 202, 8188, 73, 30978, 12, 537, 8467, 2934, 2640, 67, 739, 24899, 1132, 16, 389, 26226, 950, 1769, 203, 202, 202, 18356, 3488, 6119, 12, 3576, 18, 15330, 16, 389, 1132, 16, 389, 26226, 950, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// LC->24.10.2015 tree_scorers ОдушОбъект tree_scorer ОдушОбъект language=Russian { if context { местоим_сущ:кто{} } then 1 } tree_scorer ОдушОбъект language=Russian { if context { местоим_сущ:кто-нибудь{} } then 1 } tree_scorer ОдушОбъект language=Russian { if context { местоим_сущ:кто-то{} } then 1 } tree_scorer ОдушОбъект language=Russian { if context { местоим_сущ:кто-либо{} } then 1 } tree_scorer ОдушОбъект language=Russian { if context { существительное:*{ одуш:одуш } } then 1 } tree_scorer ОдушОбъект language=Russian { if context { местоимение:я{ род:муж } } then 1 } tree_scorer ОдушОбъект language=Russian { if context { местоимение:я{ род:жен } } then 1 } // друзья должны были дождаться нас у леса // ^^^ tree_scorer ОдушОбъект language=Russian { if context { местоимение:я{ лицо:1 } } then 1 } // Я дождусь вас // ^^^ tree_scorer ОдушОбъект language=Russian { if context { местоимение:я{ лицо:2 } } then 1 } tree_scorer ОдушОбъект language=Russian { if context { 'себе' } then 1 } tree_scorers НеодушОбъект tree_scorer НеодушОбъект language=Russian { if context { существительное:*{ одуш:неодуш } } then 1 } tree_scorer НеодушОбъект language=Russian { if context { местоим_сущ:что-то{} } then 1 } tree_scorer НеодушОбъект language=Russian { if context { местоимение:я{ род:ср } } then 1 } tree_scorer НеодушОбъект language=Russian { if context { местоим_сущ:что{} } then 1 } tree_scorer НеодушОбъект language=Russian { if context { местоим_сущ:что-нибудь{} } then 1 } tree_scorer НеодушОбъект language=Russian { if context { местоим_сущ:что-либо{} } then 1 } // ------------------------------------ /* function int CheckVerbSubjectConcord( tree v, tree sbj ) { int res_score=0; // Для безличных глаголов проверять не надо. if( eq( wordform_class(v),ГЛАГОЛ) ) then { int sbj_number = wordform_get_coord( sbj, ЧИСЛО ); if( eq(sbj_number,-1) ) then { // Подлежащим может оказаться часть речи без категории числа. // У нас есть кое-что общее. // ^^^^^^^ if( eq( wordform_class( sbj ), МЕСТОИМ_СУЩ ) ) then sbj_number = ЧИСЛО:ЕД; else if( eq( wordform_class( sbj ), ИНФИНИТИВ ) ) then sbj_number = ЧИСЛО:ЕД; } int v_number = wordform_get_coord( v, ЧИСЛО ); // согласование по числу выполняется в любом времени if( neq( sbj_number, v_number ) ) then res_score=-10; // рассогласование по числу else { int v_tense = wordform_get_coord( v, ВРЕМЯ ); if( eq( v_tense, ВРЕМЯ:ПРОШЕДШЕЕ ) ) then { if( eq( v_number, ЧИСЛО:ЕД ) ) then { // В прошедшем времени надо сопоставить род. // Если подлежащее - местоимение Я в первом или втором лице, то род // проверять не надо: // А я и не слышала. // ^^^ ^^^^^^^ if( log_and( eq( wordform_class(sbj), МЕСТОИМЕНИЕ ), one_of( wordform_get_coord(sbj,ЛИЦО), ЛИЦО:1, ЛИЦО:2 ) ) ) then { // nothing to check } else { int sbj_gender = wordform_get_coord( sbj, РОД ); int v_gender = wordform_get_coord( v, РОД ); if( neq( sbj_gender, v_gender ) ) then res_score=-10; // рассогласование по роду } } } else { // в настоящем и будущем времени надо сопоставить число и лицо // особый случай - глагол ЕСТЬ (форма глагола БЫТЬ настоящего времени), // она не имеет признака лица. int sbj_person = wordform_get_coord( sbj, ЛИЦО ); if( eq( sbj_person, -1 ) ) then sbj_person=ЛИЦО:3; if( log_not( eqi( wordform_lexem(v), 'есть' ) ) ) then { int v_person = wordform_get_coord( v, ЛИЦО ); if( neq( sbj_person, v_person ) ) then res_score=-10; // рассогласование по лицу } } } } return res_score; } // Обычный предикат с глаголом в личной форме: // Я буду читать сказку // ^^^^^^^^^^^^^ // // Безличная конструкция: // от этого мне было жаль отказываться // ^^^ ^^^^ ^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian generic { if context { инфинитив:*{}.{ v=<LEFT_AUX_VERB>глагол:*{} sbj=<SUBJECT>*:*{} } } then CheckVerbSubjectConcord(v,sbj) } // Суд вынес решение // ^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian generic { if context { v=глагол:*{}.sbj=<SUBJECT>*:*{} } then CheckVerbSubjectConcord(v,sbj) } */ // ------------------------------------ // В предложении БЕЖАТЬ НА УРОК понижаем достоверность распознавания УРОК как формы слова УРКА, // предпочитая неодушевленные объекты. tree_scorer language=Russian { if context { rus_verbs:бежать{}.предлог:на{}.ОдушОбъект } then -1 } // пойти на урок // ^^^^^ tree_scorer language=Russian { if context { rus_verbs:пойти{}.предлог:на{}.ОдушОбъект } then -1 } // Стали слышны крики играющих детей // ^^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:*{}.<OBJECT>существительное:сталь{падеж:дат} } then -10 } // давно хотел взять его рабочий телефон. // --> неодушевленные обычно не хотят tree_scorer language=Russian { if context { rus_verbs:хотеть{}.<SUBJECT>НеодушОбъект } then -2 } tree_scorer language=Russian { if context { rus_verbs:захотеть{}.<SUBJECT>НеодушОбъект } then -2 } //+tree_scorer language=Russian { if context { rus_verbs:перехотеть{}.<SUBJECT>НеодушОбъект } then -2 } // ------------------------------------------------------ // Чтобы подавить связывание глагола с предложным паттерном в конструкции: // завтракать яичницей с беконом // ^^^^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:завтракать{}.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} } } then -10 } tree_scorer language=Russian { if context { существительное:*{ одуш:неодуш <в_класс>существительное:еда{} } .предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} падеж:твор } } then 2 } // Обычно ЯВЛЯТЬСЯ можно кому-то, а не чему-то // Цена является денежным выражением стоимости. // ^^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:являться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:явиться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } } then -10 } // обрушивать на головы врагов // ^^^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обрушивать{}.<OBJECT>существительное:*{ одуш:одуш падеж:вин} } then -10 } // Мы подали им руку помощи. // ^^^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подать{}.<OBJECT>местоимение:я{ падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } } then 2 } // Белки прячутся в дупле tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:прятаться{}.<SUBJECT>ОдушОбъект } then 2 } // им пришлось идти боком. // ^^ ^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:пришлось{}.<SUBJECT>*:*{ падеж:дат } } then 2 } // Основным доводом явилось беспокойство за сохранение здоровой экологической обстановки. // ^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { существительное:беспокойство{}.предлог:за{}.*:*{падеж:вин} } then 2 } // Команды-победительницы в каждой номинации получили сертификаты на спутниковые тарелки. // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { существительное:сертификат{}.предлог:на{}.*:*{падеж:вин} } then 2 } // Поводом для раскрытия банковской тайны могут стать подозрения в нарушении налогового законодательства // ^^^^^^^^^^^... tree_scorer language=Russian { if context { существительное:повод{}.предлог:для{} } then 2 } // - Вы знали, что перевоплощаться в существа другого биологического вида запрещено сроком на шесть месяцев? // ^^^^^^^^^ tree_scorer language=Russian { if context { существительное:срок{падеж:твор}.предлог:на{} } then 5 } // различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе // ^^^^^^^^^^^... tree_scorer language=Russian { if context { существительное:политика{}.предлог:по{} } then 2 } // Она не могла оторвать взгляда от их грубой подошвы и толстых ниток, прошивающих ботинки по краям. // ^^^^^^^^ ^^... tree_scorer language=Russian { if context { rus_verbs:оторвать{}.предлог:от{} } then 2 } // Предварительное расследование пока исключает вмешательство членов экипажа в работу системы пожаротушения. tree_scorer language=Russian { if context { существительное:вмешательство{}.предлог:в{}.*:*{падеж:вин} } then 2 } // Европейский союз готов присоединиться к украинско-российским переговорам по пересмотру цены на газ // ^^^^^^^^^^^^^^... tree_scorer language=Russian { if context { существительное:переговоры{}.предлог:по{}.*:*{падеж:дат} } then 2 } // Ведь и в Мадриде, и в Барселоне начиналось именно с шумихи вокруг их гастрольной поездки... // ^^^^^^^^^^^^^^... tree_scorer language=Russian { if context { существительное:шумиха{}.предлог:вокруг{} } then 2 } // проводили мероприятие по выявлению лиц , занимающихся изготовлением контрафактных лекарств // ^^^^^^^^^^^^^^^^... tree_scorer language=Russian { if context { существительное:мероприятие{}.предлог:по{}.*:*{падеж:дат} } then 2 } // Ведь не была же она настолько наивна, чтобы верить во всю эту чушь насчет надежной мужской руки // ^^^^^^^^^^^... tree_scorer language=Russian { if context { существительное:чушь{}.предлог:насчет{} } then 2 } // Они занимались распространением наркотиков среди посетителей этого увеселительного заведения. // ^^^^^^^^^^^^^^^^ ^^^^^ tree_scorer language=Russian { if context { существительное:распространение{}.предлог:среди{}.*:*{падеж:род} } then 2 } // Этот фильм посвящен попытке человека освободиться от своего прошлого, начать новую жизнь // ^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { rus_verbs:освободиться{}.предлог:от{}.*:*{падеж:род} } then 2 } // старик прав : все имеет свою цену. // ^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:правый{ краткий число:ед род:муж }.<SUBJECT>*:*{ падеж:им род:муж число:ед } } then 2 } // тем временем надо приготовить лодки. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приготовить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Мы выбрали его секретарём нашей организации. // ^^^^^^^ ^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выбрать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>существительное:*{ падеж:твор } } } then 3 } // При жизни его не ценили. // ^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ценить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // разгрести в задачах залежи // ^^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разгрести{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } } then 2 } // император осторожно коснулся пальцами белой перчатки. // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.{ <OBJECT>*:*{ падеж:твор } <OBJECT>*:*{ падеж:род } } } then 4 } // именно поэтому она собиралась предложить им очень простой выбор. // ^^^^^^^^^^ ^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предложить{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>*:*{ падеж:вин } } } then 1 } // девушка смутно ощущала тепло. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ощущать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Томас внимательно рассматривал дома. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассматривать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Ричард обвел глазами окрестности. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обвести{}.{ <OBJECT>*:*{ падеж:твор } <OBJECT>*:*{ падеж:вин } } } then 4 } // император осторожно коснулся пальцами белой перчатки. // ^^^^^^^^ ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.*:*{ падеж:род } } then 1 } // собирать щеткой крошки со стола // ^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:собирать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Глагол ТРУБИТЬ обычно не присоединяет одушевленное прямое дополнение: // трубить о поимке разбойников tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:трубить{}.<OBJECT>*:*{ одуш:одуш } } then -10 } // Глагол СЛАГАТЬ обычно не присоединяет одушевленное прямое дополнение: // слагать о подвигах викингов tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слагать{}.<OBJECT>*:*{ одуш:одуш } } then -10 } // семья арендовала домик у владельца tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:арендовать{}.предлог:у{}.*:*{ падеж:род одуш:одуш } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:арендовать{}.предлог:у{}.местоимение:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:арендовать{}.предлог:у{}.местоим_сущ:*{ падеж:род } } then 2 } // укрыться от маньяка в доме // ^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:укрыться{}.предлог:в{}.*:*{ падеж:предл } } then 2 } // уединяться с подругой в доме // ^^^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:уединяться{}.предлог:в{}.*:*{ падеж:предл } } then 2 } // Дни стали короче. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:стать{}.прилагательное:*{ степень:сравн } } then 2 } // Чтобы устранить вариант с творительным падежом: // причинить животным страдания // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:причинить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 4 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:причинять{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 4 } // запах реки сделался сильнее. // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделаться{}.прилагательное:*{ степень:сравн } } then 2 } // У вас есть чистый лист бумаги и конверт? // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{ время:настоящее }.предлог:у{}.*:*{ падеж:род } } then 2 } // знакомая опасность казалась страшнее. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:казаться{}.прилагательное:*{ степень:сравн } } then 2 } // день будет становиться короче и немного тоскливее // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:становиться{}.прилагательное:*{ степень:сравн } } then 2 } // Снимаем омонимию кратких форм ЗАМЕТНЫЙ-ЗАМЕТЕННЫЙ: // Юпитер заметен невооруженным взглядом // ^^^^^^^ tree_scorer language=Russian { if context { прилагательное:заметный{}.<OBJECT>'взглядом' } then 2 } /* // Студентка села за стол и начала читать журнал. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:начать{}.инфинитив:*{ вид:несоверш } } then 2 } */ // Село должно отпраздновать окончание страды // ^^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:должный{ КРАТКИЙ }.инфинитив:*{} } then 2 } // ПОРА с инфинитивом обычно является безличным глаголом: // пора учиться мыслить шире. tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:пора{}.инфинитив:*{} } then 2 } // Быть сильным в чем-то неодушевленном: // Он не силён в математике. // ^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:сильный{КРАТКИЙ}.'в'.существительное:*{ одуш:неодуш } } then 2 } // дождаться сладкого tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дождаться{}.<OBJECT>НеодушОбъект{ падеж:род } } then 2 } // --------------------------------------------------------------------------- // Дать+местоимение - обычно местоимение в дательном падеже: // Я не дам им ничего // ^^^^^^ // просто они дали выход злости. // ^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 5 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 5 } // Артиллерии дам много. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}.{ <OBJECT>*:*{ ПАДЕЖ:РОД } наречие:много{} } } then 6 } // --------------------------------------------------------------------------- // Подавим вариант с Генри/твор.п./ // Генри уловил кусочек фразы. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:уловить{}.<OBJECT>*:*{ одуш:одуш падеж:твор } } then -5 } // высокие колеса подняли тучи пыли. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднять{}.<OBJECT>существительное:туча{ падеж:вин }.'пыли' } then 3 } // причинить животным страдания // ^^^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:причинить{}.<OBJECT>'страдания'{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:причинять{}.<OBJECT>'страдания'{ падеж:вин } } then 2 } // Зачерпывать пюре большой ложкой // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зачерпывать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } } then 1 } // причинить животным страдания tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } } then 1 } // ТРЕБОВАТЬ обычно присоединяет неодушевленные в родительном падеже: // наша честь требует свободы. // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:требовать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } } then 1 } // Предпочтительно такое связывание, чтобы подлежащее для ПРИВЫКНУТЬ было обушевленным, // либо было прямое дополнение в виде неодуш. объекта // мечом привык решать любой спор. // ^^^^^^ ^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { глагол:привыкнуть{}.<SUBJECT>существительное:*{ одуш:неодуш } } then -2 } // всем нужно спать на мягкой кровати // ^^^^^^^^^^ tree_scorer language=Russian { if context { 'нужно'.'всем'{ падеж:дат } } then 1 } // Для модального глагола, к которому прикреплен инфинитив, нежелательно // прикреплять еще и прямое дополнение: // // хочу все это понять // ^^^^ ^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:хотеть{}.{ <INFINITIVE>*:*{} <OBJECT>*:*{} } } then -1 } // чрезвычайная эмоциональная живость и легкомысленность партнера может меня обижать // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // происходящее теряет всякое значение. // ^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:терять{}.<OBJECT>существительное:значение{ падеж:вин } } then 2 } // пытаюсь не уснуть, выпивая много крепкого кофе, и заедая его шоколадом // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заедать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 2 } // Чтобы подавить распознавание БЫЛИ как существительного: // // Обвиняемые были освобождены в зале суда // ^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { 'были'{ class:глагол }.{ <SUBJECT>прилагательное:*{ число:мн } <RHEMA>прилагательное:*{ краткий страд число:мн } } } then 1 } // кот спит и видит мышей во сне // ^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеть{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } // Одушевленные субъекты обычно СПЯТ, а не СПАДАЮТ // кенгуру, свернувшись клубком, спал // ^^^^^^^ ^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:спать{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } } then 1 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:спасть{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } } then -4 } // ГРЕТЬ ожидает прямое дополнение в вин.п.: // Я хочу попить чаю, греющего душу // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:греть{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } } then 1 } // Кошки пили сливки несколько дней подряд // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } } then 1 } // Глагол БЫТЬ предпочинает паттер В+сущ в предл. падеже, а не в винительном: // машина была в пути // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:быть{}.предлог:в{}.*:*{ падеж:предл } } then 1 } // настоящий смех приносит облегчение. // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приносить{}.<OBJECT>существительное:облегчение{падеж:вин} } then 2 } // дважды раздался пронзительный свист. // ^^^^^^^^ ^^^^^ wordentry_set То_Что_Раздается_Как_Звук=существительное:{ шум, свист, стук, звук, сигнал, рев, крик, бормотание, слово, фраза, гул, хохот, плач, визг, хор, треск, смех, скрип, вопль, звон, выстрел } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:раздаться{}.<SUBJECT>То_Что_Раздается_Как_Звук } then 1 } // Обычно одушевленный субъект чешет неодушевленный предмет: // // Гарри почесал кончик носа. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:почесать{}.{ <SUBJECT>существительное:*{ падеж:им одуш:одуш } <OBJECT>существительное:*{ падеж:вин одуш:неодуш } } } then 1 } // цветок придал девушке уверенности. // ^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } } then 1 } // глухой рев наполнил окрестности. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:наполнить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } } then 1 } // неторопливо допил прохладный сок. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:допить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин <в_класс>существительное:напиток{} } } then 1 } /* // Мы помогли ему влезть в лодку. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 5 } */ /* // Разрешите вас пригласить? // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пригласить{}.<OBJECT>*:*{ падеж:вин } } then 1 } */ // неторопливо допил прохладный сок. // ^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:допить{}.<OBJECT>существительное:*{ падеж:вин одуш:неодуш <в_класс>существительное:напиток{} } } then 1 } // Он научил меня играть в шахматы. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:научить{}.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } } then 5 } // Миша допил чай // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:допить{}.существительное:*{ падеж:вин одуш:неодуш } } then 1 } // Миша выпил чай // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выпить{}.существительное:*{ падеж:вин одуш:неодуш } } then 1 } // Он смотрит на вещи просто. // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.предлог:на{}.существительное:*{ падеж:вин } } then 1 } // Оставь книгу у Лены. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставить{}.предлог:у{}.существительное:*{ одуш:одуш } } then 1 } // кенгуру наловил детенышам мышей своими лапами // ^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:наловить{}.<OBJECT>*:*{ падеж:род } } then 1 } // Автор воскресил героя из небытия // ^^^^^^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:воскресить{}.предлог:из{}.'небытия' } then 1 } // Коля вызвался помочь с математикой // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.предлог:с{}.существительное:*{ одуш:неодуш } } then 1 } // Поищите это слово в словаре. // ^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } } then 1 } // Всё это нашло отражение в его книге. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.<OBJECT>существительное:отражение{}.предлог:в{} } then 3 } // Я никого не встретил // ^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } } then 1 } // Никого не встретить tree_scorer language=Russian { if context { инфинитив:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } } then 1 } // Он никого не видел там кроме неё. // ^^^^^^ ^^ ^^^^^ tree_scorer language=Russian { if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } } then 1 } // напасть на спящих // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напасть{}.предлог:на{}.*:*{ падеж:вин } } then 1 } // Мы с Мишей читали сказку tree_scorer language=Russian { if context { местоимение:я{}.предлог:с{}.существительное:*{ падеж:твор одуш:одуш } } then 1 } // Мы с ней сидели за одной партой. // ^^^^^^^^ tree_scorer language=Russian { if context { местоимение:я{}.предлог:с{}.местоимение:я{ падеж:твор } } then 1 } // Мы с ним были на концерте. tree_scorer language=Russian { if context { местоимение:я{}.предлог:с{}.'ним'{ род:муж } } then 1 } // Аллах сотворил всякое животное из воды. // ^^^^^^^^ ^^^^^^^ tree_scorer language=Russian { if context { rus_verbs:сотворить{}.предлог:из{} } then 2 } // Аллегра не сводила глаз с мужа. // ^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { rus_verbs:сводить{}.{ <OBJECT>"глаз"{число:мн} предлог:с{}.*{падеж:твор} } } then 2 } // А вы были помолвлены с Лиллианой. // ^^^^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:помолвленный{}.предлог:с{}.*{падеж:твор} } then 2 } // А ты с ним плохо обращаешься? // ^^^^^ ^^^^^^^^^^^ tree_scorer language=Russian { if context { rus_verbs:обращаться{}.предлог:с{}.*{падеж:твор} } then 2 } // Он относится к бедному товарищу с горячим участием. // ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { глагол:*{}.'с'.'участием' } then 1 } tree_scorer language=Russian { if context { инфинитив:*{}.'с'.'участием' } then 1 } tree_scorer language=Russian { if context { деепричастие:*{}.'с'.'участием' } then 1 } tree_scorer language=Russian { if context { прилагательное:*{ причастие }.'с'.'участием' } then 1 } // Она оправдала неявку на занятия болезнью. // ^^^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оправдать{}.<OBJECT>*{ падеж:твор } } then 1 } // жаждать мести tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:жаждать{}.<OBJECT>'мести'{ падеж:род } } then 1 } // Он доводится мальчику дядей // ^^^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доводиться{}.<OBJECT>*:*{ падеж:твор } } then 1 } // принести в дом бездомного щенка // ^^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принести{}.<OBJECT>*:*{ падеж:вин } } then 1 } // всадить пулю в сердце // ^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:всадить{}.предлог:в{}.существительное:*{ падеж:вин } } then 1 } // Усиленная работа отразилась на его здоровье. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отразиться{}.предлог:на{}.существительное:здоровье{ падеж:предл } } then 1 } #define PreferAccusObject(v) \ #begin tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:v{}.<OBJECT>*:*{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:v{}.<OBJECT>*:*{ падеж:вин } } then 1 } #end // Поэты воспели в этой оде героев PreferAccusObject(воспеть) // встретить в классе старого приятеля (встретить+вин.п.) PreferAccusObject(встретить) // встречать в лесу голодного медведя (встречать+вин.п.) PreferAccusObject(встречать) // выписать из деревни нового скакуна PreferAccusObject(выписать) // регулярная армия вытесняет из пригородов повстанцев PreferAccusObject(вытеснять) // выводить с одежды пятна (вводить + вин.п.) PreferAccusObject(выводить) // выжать максимум из машины (выжать + вин.п.) PreferAccusObject(выжать) // собраться в аудитории tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:собраться{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл <в_класс>существительное:помещение{} } } then 1 } // Глагол БОЯТЬСЯ обычно используется с прямым дополнением, причем одушевленное // дополнение стоит в винительном падеже, а неодушевленное - в родительном. // они должны научиться бояться нас. // ^^^^^^^^^^^ // Дело мастера боится. // ^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>НеодушОбъект{ падеж:род } } then 1 } // сказал Холмс, снимая крышку с курицы // ^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:снимать{}.предлог:с{}.*:*{ падеж:род } } then 2 } // Я послал книги по почте. // ^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послать{}.предлог:по{}.'почте' } then 2 } // Он разложил книги по всему столу. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разложить{}.предлог:по{}.существительное:*{} } then 1 } // Мы покормили белок. // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:покормить{}.существительное:*{ падеж:вин одуш:одуш } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:покормить{}.существительное:*{ падеж:вин одуш:одуш } } then 2 } // писатель пишет повести // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:писать{ aux stress="пис^ать" }.существительное:*{ одуш:неодуш падеж:вин } } then 1 } // Резкий порывистый ветер валит прохожих с ног. // ^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:валить{}.предлог:с{}.'ног' } then 1 } // Резкий порывистый ветер свалит тебя с ног. // ^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:свалить{}.предлог:с{}.'ног' } then 1 } // блоггер, написавший про детский приют tree_scorer language=Russian { if context { прилагательное:написавший{ aux stress="напис^авший" }.предлог:про{} } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:написать{ aux stress="напис^ать" }.предлог:про{} } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:написать{ aux stress="напис^ать" }.предлог:про{} } then 1 } // Учительница ищет в карманах шпаргалки // ^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:искать{}.существительное:*{ падеж:вин } } then 1 } // заметившими косулю медведицами // ^^^^^^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заметить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } } then -2 } // стирать белье в реке // ^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:стирать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:купить{}.предлог:у{}.существительное:*{ одуш:одуш } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:купить{}.предлог:у{}.местоимение:*{} } then 2 } // стирать прошлое из памяти tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:стирать{}.предлог:из{}.существительное:память{} } then 1 } // Боль исказила его лицо. // ^^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:исказить{}.<OBJECT>существительное:лицо{ одуш:неодуш } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:искажать{}.<OBJECT>существительное:лицо{ одуш:неодуш } } then 1 } // Подавим по возможности связывание глагола ЕСТЬ с предложным дополнением ИЗ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:есть{}.предлог:из{}.существительное:*{ <в_класс>существительное:овощ{} } } then -1 } // Винительное дополнение: // считать деньги tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:считать{}.*:*{падеж:вин} } then 1 } // Мы согласовали наши законы с беларусским законодательством tree_scorer ВалентностьГлагола language=Russian { if context { глагол:согласовать{ вид:соверш }.предлог:с{} } then 1 } // Я иду в кино. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:идти{}.{ 'в'.'кино'{ падеж:вин } <SUBJECT>местоимение:*{} } } then 1 } // Он купил игрушки для детей. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:купить{}.*:*{ падеж:вин } } then 1 } // Он занял деньги под большие проценты. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:занять{}.'деньги'{ падеж:вин } } then 1 } // его осторожность взяла верх над его жадностью // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.существительное:верх{}.предлог:над{} } then 1 } // Студенты долго ломали голову над задачей. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.{ 'голову' предлог:над{} } } then 1 } // Я не хотел вас обидеть. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.*:*{ падеж:вин } } then 2 } // Я нашёл толк в этом деле. // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.{ 'толк' предлог:в{}.существительное:*:*{ падеж:предл } } } then 1 } // Я всюду искал письмо, но нигде не мог его найти. // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.*:*{ падеж:вин } } then 2 } // Я вовсе не хотел её оскорбить. // ^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оскорбить{}.*:*{ падеж:вин } } then 2 } // Мы перебили врагов в бою. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:перебить{}.'в'.'бою' } then 1 } // Этот мотор делает 600 оборотов в минуту. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:делать{}.существительное:оборот{}.num_word:*{} } then 3 } // для ВЫУЧИТЬ желательно дополнение в винительном падеже // Он выучил меня играть в шахматы. // ^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выучить{}.*:*{ падеж:вин } } then 2 } // Будем считать, что ЭТО в роли подлежащего имеет приоритет: // Это внесло разнообразие в мою жизнь. tree_scorer ВалентностьПредиката language=Russian { if context { глагол:*{ время:прошедшее число:ед род:ср }.<SUBJECT>'это' } then 1 } // Я принёс эту книгу для вас. // ^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принести{}.предлог:для{}.местоимение:*{} } then 1 } // Глагол ИЗБРАТЬ обычно требует прямое дополнение в винительном падеже: // Академия наук избрала его почётным членом. // ^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избрать{}.*:*{ падеж:вин } } then 1 } // Глагол ПРИСЫЛАТЬ обычно требует прямое дополнение // Он присылал к должнику своих головорезов // ^^^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:присылать{}.<OBJECT>существительное:*{ падеж:вин } } then 1 } // Я никого не встретил // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.{ частица:не{} 'никого'{ падеж:род } } } then 1 } // они затопили корабли в гавани // ^^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:затопить{}.предлог:в{}.*:*{ падеж:предл } } then 1 } // Составьте предложение из этих слов. // ^^^^^^^^^ ^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:составить{}.предлог:из{}.существительное:*{ одуш:неодуш падеж:род } } then 1 } // Согрейте руки у огня. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:согреть{}.предлог:у{}.существительное:*{ одуш:неодуш падеж:род } } then 1 } // Не оставь товарища в опасности. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставить{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } // Я принёс книгу с собой. tree_scorer ВалентностьГлагола language=Russian { if context { Гл_С_Твор.'с'.'собой' } then 1 } // Наш пароход держал курс прямо на север. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:держать{}.<OBJECT>существительное:курс{ падеж:вин } } then 1 } // Антонио ни с кем не говорил // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.{ 'не' 'с'.{ 'ни' 'кем' } } } then 1 } // Я был знаком с вашим дядей. // ^^^^^^^^ tree_scorer language=Russian { if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.существительное:*{ одуш:одуш } } } then 3 } tree_scorer language=Russian { if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.местоимение:*{} } } then 3 } // Подавим родительную валентность для местоимения. // Вас требует заведующий. // ^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ ПАДЕЖ:ВИН }.<OBJECT>'вас'{падеж:вин} } then 1 } // Я научил его английскому языку. // ^^^^^^ ^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:научить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } } then 1 } // Я учу его английскому языку. // ^^^ ^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:учить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } } then 1 } // Я велел ему прийти через час. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:велеть{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } } then 1 } // Дождь помешал нам прийти. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помешать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } } then 1 } // Ведь вы сами посоветовали мне так сделать. // ^^^^^^^^^^^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посоветовать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } } then 1 } // Антонио разрешил нам рассказать об этом // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разрешить{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } } then 1 } // кенгуру наловил детенышам мышей своими лапами // ^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:наловить{}.<OBJECT>*:*{ падеж:род } } then 1 } // Характер писателя лучше всего выражается в его произведениях. // ^^^^^^^^^^^ tree_scorer language=Russian { if context { наречие:всего{}.'лучше'{ class:наречие } } then 1 } // Этот город находится к западу от Москвы. tree_scorer ВалентностьПредиката language=Russian { if context { глагол:находиться{ вид:несоверш }.<SUBJECT>существительное:*{} } then 1 } // Он находится в весьма неприятном положении. tree_scorer ВалентностьГлагола language=Russian { if context { глагол:находиться{ вид:несоверш }.предлог:*{} } then 1 } // Подавим родительный падеж: // Прошу вас. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:просить{}.местоимение:я{ падеж:вин } } then 1 } // Природа наградила его разнообразными способностями. // ^^^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:наградить{}.местоимение:я{ падеж:вин } } then 1 } // Природа одарила его прекрасными способностями. // ^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:одарить{}.местоимение:я{ падеж:вин } } then 1 } // Предпочтём винительный падеж местоимения, а не родительный. // Вас спрашивает какой-то человек. // ^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спрашивать{}.'вас'{падеж:вин} } then 1 } // Примите мой искренний привет! // ^^^^^^^ ^ tree_scorer language=Russian { if context { 'примите'{ наклонение:побуд }.'!' } then 1 } // Напишите фамилию полностью. // ^^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:написать{aux stress="напис^ать"}.наречие:полностью{} } then 1 } // Она обозвала его дураком. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обозвать{}.{ *:*{ падеж:вин } *:*{ падеж:твор } } } then 1 } // Понизим достоверность распознавания УРКА: // Девочка вообще не пошла на урок // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пойти{}.предлог:на{}.'урок'{ одуш:неодуш } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:идти{}.предлог:на{}.'урок'{ одуш:неодуш } } then 1 } // Выбираем винительный падеж: // Время работает на нас. // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:работать{}.'на'.'нас'{падеж:вин} } then 1 } // Мы пришли к заключению, что он прав. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.'к'.'заключению' } then 1 } /* tree_scorer language=Russian { if context { 'два'{ class:числительное род:муж }.существительное:*{род:жен} } then -1 } tree_scorer language=Russian { if context { 'два'{ class:числительное род:муж }.существительное:*{род:ср} } then -1 } tree_scorer language=Russian { if context { 'два'{ class:числительное род:ср }.существительное:*{род:муж} } then -1 } tree_scorer language=Russian { if context { 'два'{ class:числительное род:ср }.существительное:*{род:жен} } then -1 } tree_scorer language=Russian { if context { числительное:два{род:жен}.существительное:*{род:жен} } then 1 } tree_scorer language=Russian { if context { числительное:два{род:ср}.существительное:*{род:ср} } then 1 } */ // Уберем вариант СТАТЬ для: // // Он написал статью на русском языке. // ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:написать{ aux stress="напис^ать" }.<OBJECT>'статью'{ падеж:вин } } then 1 } // Антонио подарил ведьмёнышам пюре tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подарить{}.{ <OBJECT>существительное:*{ падеж:вин одуш:неодуш } <OBJECT>существительное:*{ падеж:дат одуш:одуш } } } then 1 } // Дайте мне хлеба. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:вин } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:род } } then 1 } /* wordentry_set НаречВремСуток=наречие:{ утром, вечером, днем, ночью } // она вечером будет есть пюре tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.{ НаречВремСуток инфинитив:*{} } } then 1 } */ // Глаголы с семантикой поедания, присоединяющие прямое дополнение в вин. падеже wordentry_set ГлаголыПоедания_Вин= { глагол:есть{}, инфинитив:есть{} } // Антонио ест пюре tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.<OBJECT>'пюре'{падеж:вин} } then 1 } /* // она утром будет есть пюре tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:утром{} } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.'утром'{ class:существительное } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.'днем'{ class:существительное } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.'вечером'{ class:существительное } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.'ночью'{ class:существительное } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:днем{} } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:вечером{} } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:ночью{} } then 1 } */ // желая стать космонавтом // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:стать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } } then 1 } // Царя над окрестностями tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:царить{}.'над'.'окрестностями' } then 1 } // Планета Юпитер не видна днём // ^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:видный{ краткий }.<ATTRIBUTE>'днем'{} } then 1 } // Подавим распознавание ПОТОМ как существительного: // вы едите пюре или суп, потом пьете чай tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<OBJECT>'потом'{падеж:твор} } then -100 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<OBJECT>'потом'{падеж:твор} } then -100 } // Для глагола ЛОВИТЬ подавляем прямое дополнение в творительном падеже, если // оно соответствует одушевленному: // Антонио опять ловит мышь несколько ночей подряд tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ловить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } } then -1 } // продавать книги tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продавать{}.<OBJECT>существительное:*{ падеж:вин } } then 1 } // мы не увидели тебя tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:увидеть{}.<OBJECT>местоимение:*{ падеж:вин } } then 1 } // Винительная валентность глагола ГОВОРИТЬ используется // только с неодушевленным дополнением. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:говорить{}.<OBJECT>*{ падеж:вин } } then -1 } // кот не видит ее tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеть{}.<OBJECT>местоимение:я{ падеж:вин } } then 1 } // кот увидел кенгуру на полу // ^^^^^^ ^^^^^^^ // Подавим вариант творительного падежа для любых дополнение, за исключением ГЛАЗ // а неодушевленные пусть будут "увидел своими глазами" tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:увидеть{}.<OBJECT>существительное:глаз{ падеж:твор } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеть{}.<OBJECT>существительное:глаз{ падеж:твор } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:увидеть{}.<OBJECT>существительное:*{ падеж:твор } } then -1 } // Дмитрий Иванович Менделеев увидел периодическую таблицу элементов во сне // ^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:увидеть{}.'во'.'сне' } then 1 } // аналогично для: // кот видит кенгуру на полу tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеть{}.<OBJECT>существительное:*{ падеж:твор } } then -1 } // Для глагола ВСТРЕТИТЬ подавим прямое дополнение в творительном падеже, если // оно - одушевленный объект: // ведьмёныш встретил Антонио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:встретить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } } then -1 } // Аналогично: ведьмёныш встречал Антонио веселым криком tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:встречать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } } then -1 } wordentry_set ЧтоМожноДелатьСЧаем= { инфинитив:налить{}, глагол:налить{} } tree_scorer ВалентностьГлагола language=Russian { if context { ЧтоМожноДелатьСЧаем.<OBJECT>'чаю'{падеж:парт} } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:ловить{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } // мыть руки с мылом tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:мыть{}.'с'.'мылом' } then 1 } // Я мою руки с мылом tree_scorer ВалентностьГлагола language=Russian { if context { глагол:мыть{}.'с'.'мылом' } then 1 } // кошки собираются ловить хозяину в амбаре мышь tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:ловить{}.'в'.'амбаре' } then 1 } // Мы боремся все доступными средствами с ошибками в программе tree_scorer ВалентностьГлагола language=Russian { if context { глагол:бороться{}.'с'.'ошибками' } then 1 } // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:высадиться{}.'для'.'поиска' } then 1 } // стипендия студента университета дружбы народов, живших в союзных республиках бывшего СССР tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:живший{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } // студенты университета, построенного в СССР tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:построенный{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } // группа студентов университета дружбы народов, основанного в СССР tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:основанный{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:пропагандировавшийся{}.предлог:в{}.существительное:*{ падеж:предл } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { 'сыплет'{class:глагол}.<SUBJECT>существительное:дождь{ падеж:им } } then 1 } tree_scorer language=Russian { if context { безлич_глагол:стало{}.'всем'{ class:прилагательное падеж:дат} } then 1 } // давай-ка выпей молока tree_scorer ВалентностьГлагола language=Russian { if context { глагол:выпить{}.'молока'{class:существительное} } then 1 } // лежащий на полу tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:лежащий{}.предлог:на{}.'полу'{падеж:мест} } then 1 } // Подавим распознавание ДНЁМ как существительного в творительном падеже. // // кошки днем обычно ели и дремали // ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:есть{}.<OBJECT>существительное:день{ падеж:твор } } then -1 } // Несмотря на появляющуюся родительную валентность в отрицательной форме глагола, // местоимения её и его надо брать только в аккузативе. // она её не съест tree_scorer ВалентностьГлагола language=Russian { if context { глагол:съесть{}.'ее'{ падеж:вин } } then 1 } /* // Планета Марс видна утром tree_scorer language=Russian { if context { прилагательное:видный{}.наречие:утром{} } then 1 } */ /* // Повысим достоверность безличного глагола. // // Грести стало труднее // ^^^^^ tree_scorer language=Russian { if context { 'стало'{class:безлич_глагол} } then 1 } */ // Для глагола КУПИТЬ надо подавлять связывание с прямым дополнением в родительным падеже // для живых существ. // Ну же, купите слона! tree_scorer ВалентностьГлагола language=Russian { if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ падеж:род } } then -1 } // купи кефиру tree_scorer ВалентностьГлагола language=Russian { if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:НЕОДУШ падеж:парт } } then 4 } // налей мне воды // ^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:налить{}.<OBJECT>'воды'{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:лежать{}.'в'.'углу' } then 1 } // ОСВЕТИТЬ можно обычно КОМУ-ТО, а не чему-то: // отблеск молнии осветил часового. // ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осветить{}.существительное:*{ падеж:дат одуш:неодуш } } then -10 } // Он ездит на работу на автобусе. // ^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ездить{}.предлог:на{}.существительное:*{ падеж:предл одуш:неодуш <в_класс>существительное:транспорт{} } } then 2 } // Его успех доставил ей радость. // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } } then 2 } /* // Предотвращаем отрыв слова ЭТОТ, ЭТОЙ и т.д. от существительного. // Роберт улыбнулся этой мысли. // ^^^^^^^^^^ tree_scorer language=Russian { if context { существительное:*{}.<ATTRIBUTE>прилагательное:этот{} } then 2 } */ // Речки разлились и дороги стали непроходимы. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:стать{}.прилагательное:*{ краткий } } then 1 } // укрыться от дождя под навесом // ^^^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:укрыться{}.предлог:под{}.НеодушОбъект } then 2 } // Мул - помесь осла и лошади. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { существительное:помесь{}.существительное:*{}.союз:и{} } then 1 } // Олег обвел взглядом окрестности. // ^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обвести{}.<OBJECT>*:*{ падеж:вин } } then 1 } // Олег хмуро окинул взглядом убитого. // ^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окинуть{}.<OBJECT>*:*{ падеж:вин } } then 1 } // мои предки построили его собственными руками. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:построить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 5 } // иначе им грозит беда. // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:грозить{}.<OBJECT>*:*{ падеж:дат } } then 1 } // Джим поискал глазами своего коня. // ^^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } // вера дает им силу. // ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:давать{}.<OBJECT>*:*{ падеж:дат } } then 1 } // им дорого обойдется сегодняшний бой. // ^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обойтись{}.<OBJECT>*:*{ падеж:дат } } then 1 } // киммериец молча пожал ей руку. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } } then 1 } // ей ответил пронзительный яростный визг. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ответить{2}.<OBJECT>местоимение:я{ 1 падеж:дат } } then 1 } // Он ответил Джо tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ответить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } // зачем давать им пустую надежду. // ^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } } then 2 } // тебе следовало оставить ей записку. // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } } then 2 } // маленький желтый череп улыбнулся ей. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:улыбнуться{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } // Томас швырнул ей птицу. // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:швырнуть{1}.{ <OBJECT>ОдушОбъект{ 2 падеж:дат } <OBJECT>*:*{ падеж:вин } } } then 2 } // дом чрезвычайно понравился ей. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // меч им явно нравился. // ^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:нравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // некоторым действительно нравится моя работа. // ^^^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:нравиться{}.<OBJECT>прилагательное:*{ падеж:дат число:мн ~краткий } } then 4 } // лунный свет помогал им. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>*:*{ падеж:дат } } then 3 } // им необходимо было помочь. // ^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // мой отец убит им. // ^^^^^^^ tree_scorer language=Russian { if context { прилагательное:убитый{}.<OBJECT>*:*{ падеж:твор } } then 1 } // ей надо уйти отсюда. // ^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:надо{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } } then 1 } // ей вдруг захотелось уйти. // ^^^ ^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:захотелось{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } } then 1 } // капитан пожал им руки. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пожать{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } } then 2 } // хозяин жеребца снова закричал. (закричать можно ЧТО-ТО, но не КОГО-ТО) tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:закричать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then -100 } // ей явно понравился ответ. // ^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 } // остальным предстояло помогать им. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 } // им стало вдруг зябко. // ^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:стало{}.ОдушОбъект{ падеж:дат } } then 1 } // нам стало жалко бедного котенка tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:жалко{}.ОдушОбъект{ падеж:дат } } then 2 } // император осторожно коснулся пальцами белой перчатки. // ^^^^^^^^ ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.<OBJECT>*:*{ падеж:род } } then 1 } // обычно ПРОТЯНУТЬ кому-то, а не чему-то: // тот протянул руку помощи. // ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -5 } // возле всякой двери тебя ждала такая же ловушка. // ^^^^^^^^^^ // однако сперва ее ждало глубокое разочарование. // ^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подождать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } // однако ему удалось открыть нечто интересное. // ^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открыть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 } // однако название мне удалось прочитать. // ^^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прочитать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 } // пройти можно ЧТО-ТО: // ты уже прошел его так много раз. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пройти{}.<OBJECT>ОдушОбъект{ падеж:вин } } then -1 } /* tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пройти{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 } */ // злость прошла довольно давно. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пройти{}.<SUBJECT>НеодушОбъект } then 1 } // затем стал внимательно изучать глаз юноши. // ^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:изучать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // комната ожидания полна народу. // ^^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:полный{ краткий }.существительное:*{ падеж:род } } then 1 } tree_scorer language=Russian { if context { прилагательное:полный{ краткий }.существительное:*{ падеж:парт } } then 1 } // развалиться на части tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:развалиться{}.'на'.'части'{ падеж:вин } } then 2 } // ВЗЯТЬ можно КОМУ-ТО, а не ЧЕМУ-ТО: // полковник взял микрофон внутренней связи. // ^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -5 } // оставался единственный способ проверить корабль. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:проверить{}.<OBJECT>*:*{ падеж:вин } } then 1 } // ТРЕБОВАТЬ можно кому-то, а не чему-то: // моя месть требует радости охоты. // ^^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:требовать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -5 } // ПРОДОЛЖИТЬ можно ЧТО-ТО неодушевленное: // вскоре отряд продолжил путь. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then -1 } // Ломать душу tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 } // я доволен им // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:довольный{ краткий }.<OBJECT>*:*{ падеж:твор } } then 2 } // Обычно получить можно кому-то, а не чему-то: // поэтому хотим получить максимум информации. // ^^^^^^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:получить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // пришла пора сделать следующий шаг. // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:прийти{}.<SUBJECT>существительное:пора{}.инфинитив:*{} } then 1 } // убить КОГО-ТО: // ты должен его убить! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // мне едва удалось его спасти. // ^^^ ^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:удалось{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 } // им удалось вытащить его из озера. // ^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:удалось{}.<SUBJECT>*:*{ падеж:дат } } then 1 } // ЕДА не может быть продавцом: // В булочной продают хлеб, булки, печенье. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:продавать{}.<SUBJECT>существительное:*{ <в_класс>существительное:еда{} } } then -100 } // ОБЪЯСНИТЬ можно обычно кому-то: // происхождение информации объясню позднее. // ~~~~~~~~~~ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 } #region СОЗДАВАТЬ // если получатель действия находится слева от глагола, то штрафуем: // банки памяти создавали самую большую проблему. // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{ 2 }.<OBJECT>*:*{ падеж:дат 1 } } then -1 } // Но компенсируем предыдущее правило, если получатель - одушевленный: // нам создали тепличные условия // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{ 2 }.<OBJECT>ОдушОбъект{ падеж:дат 1 } } then 1 } #endregion СОЗДАВАТЬ // Обычно ПОКАЗАТЬСЯ можно КОМУ-ТО: // показалась машина местной полиции. // ^^^^^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 } // БЕЖАТЬ можно чем-то неодушевленным, например - БЕРЕГОМ: // бегущим по берегу псом // ^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бежать{}.<OBJECT>ОдушОбъект{ падеж:твор } } then -100 } // Чтобы подавить распознавание существительным "БЫЛЬ": // "Обвиняемые были освобождены в зале суда" // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { глагол:быть{ 2 }.<SUBJECT>прилагательное:*{ падеж:им ~краткий степень:атриб 1 } } then 2 } // ПОИСКАТЬ обычно можно КОМУ-ТО: // Давайте поищем примеры реализации этой функции // ^^^^^^ ~~~~~~~~~~ ~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // Обычно ПРИХОДИТ КОМУ-ТО, а неодушевленный реципиент возможет лишь в // особых оборотах типа КОНЕЦ ПРИШЕЛ ЭТОЙ АФЕРЕ. // неизвестно откуда пришло вдруг чувство опасности. // ^^^^^^ ~~~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 } // советую вам исправить свою ошибку. // ^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:советовать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // Подавим связывание ПРИШЛО и ПОЗАБОТИТЬСЯ исходя из того, что обычно // только одушевленные субъекты приходят сделать что-то: // однако пришло время позаботиться о собственной безопасности. // ^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 } // Зайти можно КОМУ-ТО // сам зашел снаружи конструкции противника. // ^^^^^ ~~~~~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // обычно глагол ЗАНЯТЬ идет с винительным дополнением: // эти приготовления заняли целый день. // ^^^^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:занять{}.<OBJECT>*:*{ падеж:вин } } then 1 } // Сжать обычно можно КОМУ-ТО: // Олег изо всех сил сжал челюсти. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сжать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // после начала битвы прошли считанные секунды. // ^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:пройти{}.<SUBJECT>ИнтервалВремени{ ПАДЕЖ:ИМ } } then 1 } // желаю тебе найти принца. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:желать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 1 } // Он рекомендовал мне сделать это. // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рекомендовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 1 } // Он угрожал мне бросить работу. // ^^^^^^^ ^^^ ~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угрожать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 1 } // позволю себе напомнить историю вопроса. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позволить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 1 } // Олег хмуро окинул взглядом убитого. // ^^^^^^ ^^^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окинуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'взглядом' } } then 1 } // где же моя благодарность? // ^^^^^^ ^^^^^^^^^^^^^ tree_scorer language=Russian { if context { наречие:где{}.{ частица:же{} существительное:*{ падеж:им } } } then 1 } // кому хочется есть // ^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 1 } // нам нужно только доставить его туда. // ^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:нужно{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 2 } // ТОРЖЕСТВОВАТЬ можно ЧТО-ТО неодушевленное: // Весь день и весь вечер шумел и торжествовал народ по всему королевству // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:торжествовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -100 } // МЕШАТЬ кому-то ДЕЛАТЬ что-то // страх мешал ей плакать. // ^^^^^ ^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:мешать{}.{ <OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } инфинитив:*{} } } then 2 } // ПОВТОРИТЬ можно обычно КОМУ-ТО, а не ЧЕМУ-ТО // мастер песни повторил вопрос. // ~~~~~ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:повторить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 } // вскоре подошел поезд метро. // ^^^^^^^ ~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подойти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 } // ОТКРЫВАТЬСЯ можно обычно КОМУ-ТО // новый мир открывался после каждой мили пути. // ^^^^^^^^^^ ~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открываться{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 } // Обычно СЛОЙ покрывает что-то, даже если порядок слов обратный нормальному: // пол покрывал толстый слой пыли. // ^^^^^^^^ ^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:покрывать{}.{ <SUBJECT>существительное:слой{} НеодушОбъект{ ПАДЕЖ:ВИН } } } then 2 } // Ей нравится ходить туда. // ^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:нравилось{}.<SUBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } // оставался единственный способ проверить корабль. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:проверить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // кому вы отдали его? // ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } } then 2 } // кому может понадобиться старая чужая лодка? // ^^^^ ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } } then 2 } // Не смей мне врать! // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:врать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 2 } // меня все здесь боятся! // ^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then 1 } // Он мучает её своим бесчувствием. // ^^^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:мучить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 1 } // почему ты позволил им упасть? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позволить{}.<OBJECT>*:*{ падеж:дат } } then 2 } // разве обычные люди могут читать мысли? // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:читать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:читать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 } // НАЗЫВАТЬ обычно идет с винительным дополнением: // все его называют сегодня мальчиком. // ^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Подавляем присоединение послелогов к существительным: // недалеко от него лежал человек лицом вниз. // ~~~~~~~ ^^^^^^^^^^ tree_scorer language=Russian { if context { существительное:*{}.послелог:вниз{} } then -10 } tree_scorer language=Russian { if context { существительное:*{}.послелог:вверх{} } then -10 } tree_scorer language=Russian { if context { существительное:*{}.послелог:вперед{} } then -10 } // Показывать на одушевленного (вин) - это важно, если объект несклоняемый: // Вадим показал на Элен // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показать{}.предлог:на{}.ОдушОбъект{ падеж:вин } } then 1 } // пора им всем возвращаться домой. // ~~~~~~~ ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:возвращаться{}.ОдушОбъект{ падеж:твор } } then -10 } // мама души не чаяла в своих детях // ~~~~ ^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:чаять{}.<OBJECT>существительное:душа{} } then 30 } // Комар носа не подточит. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подточить{}.{ частица:не{} <OBJECT>существительное:нос{} } } then 30 } /* // с тех пор ты видел его всего несколько раз. // ^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { наречие:всего{}.наречие:несколько{}.существительное:раз{} } then 2 } */ // Руперт вопреки себе улыбнулся. // ^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:вопреки{} } then 2 } // вам следует проверить Марину согласно инструкции. // ^^^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:согласно{} } then 2 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:согласно{} } then 2 } // убийство для них естественно. tree_scorer language=Russian { if context { прилагательное:естественный{}.предлог:для{} } then 2 } // Пусть предложное дополнение с У присоединяется к глаголу, а не к существительному: // ноги у меня болели. // ^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:у{} } then 2 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:у{} } then 2 } // Антон ее так назвал. // ^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } } then 1 } // Наречие ЧАСТО служит косвенным признаком изъявительной, а не императивной формы глагола: // ты часто ешь хлеб // ^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ наклонение:побуд }.наречие:часто{} } then -2 } // Наречие ОЧЕНЬ служит косвенным признаком изъявительной, а не императивной формы глагола: // вы очень любите ягоды tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ наклонение:побуд }.наречие:очень{} } then -2 } // несколько дней спустя путников ожидал приятный сюрприз. // ^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ожидать{}.ОдушОбъект{ ПАДЕЖ:ВИН } } then 1 } // ПРИВЛЕЧЬ обычно можно КОГО-ТО одушевленного: // Его привлекли к ответственности за нарушение порядка. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:привлечь{}.ОдушОбъект{ ПАДЕЖ:ВИН } } then 1 } // Его целый год держали в тюрьме. // ^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:держать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 4 } // ОБЕЩАТЬ КОМУ-ТО СДЕЛАТЬ что-то: // ты обещал мне показать корабль! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 } // чиновник приказал ему открыть два кожаных мешка. // ^^^^^^^^ ^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приказать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 5 } // ++++++++++++++++++++++++++++++++++++++++ // мне обещали все вернуть назад tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 5 } // ++++++++++++++++++++++++++++++++++++++++ // мне обещали все вернуть назад // Его гордость не позволяла ему просить об одолжении. // ^^^^^^^^^ ^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позволять{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позволить{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 } // такое устройство для моих целей бесполезно. // ~~~~~~~~~~ ^^^ ^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:бесполезный{}.предлог:для{} } then 2 } // ДАТЬ отчет можно обычно КОМУ-ТО, а не чему-то: // Он дал подробный отчёт о своей поездке. // ^^^ ^^^^^ ~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}.{ <OBJECT>существительное:отчет{} <OBJECT>НеодушОбъект{ПАДЕЖ:ДАТ} } } then -10 } // отстегнуть маме денег tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отстегнуть{}.{ <OBJECT>НеодушОбъект{ падеж:род } <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} } } then 5 } // все вас боятся // ~~~~~~~ tree_scorer language=Russian { if context { 'вас'.'все'{class:прилагательное} } then -100 } // Я работаю учителем в сельской школе // ^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:работать{}.предлог:в{}.*:*{падеж:предл} } then 2 } // небеса для меня закрыты. // ^^^ ^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:закрытый{}.предлог:для{} } then 2 } // Это такое трудное слово, что он не может его запомнить. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запомнить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Его утомляла долгая ходьба. // ^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомлять{}.ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомить{}.ОдушОбъект{ падеж:вин } } then 2 } // но где удалось его добыть? // ^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:добыть{}.НеодушОбъект{ падеж:вин } } then 2 } // кладбище от моря довольно далеко // ~~~~~~~~ ^^ ^^^^^^ tree_scorer language=Russian { if context { прилагательное:далекий{}.предлог:от{} } then 2 } // мы внедряем в жизнь идеи великих ученых // ^^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрять{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрить{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 } // неужели разговор его окончательно сломал? // ^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:переломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обламывать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 } // Критика должна составлять душу журнала. // ^^^^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:составлять{1}.<OBJECT>НеодушОбъект{ 2 ПАДЕж:ВИН} } then 1 } // ПОРАЗИТЬ обычно можно КОГО-ТО, а не чего-то: // однако его глубоко поразило одно событие. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then 2 } // такое положение вещей его вполне устраивает. // ^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устраивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устроить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // Обычно ПОИСКАТЬ можно КОМУ-ТО, а не чему-то: // Давайте поищем примеры реализации этой функции tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ПАДЕж:ДАТ} } then -1 } // Давать КОМУ-ТО ЧЕГО-ТО: // Рита дает девочке хлеба. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:давать{}.{ <OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } } then 5 } // Я дам им чаю // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <OBJECT>*:*{ ПАДЕЖ:ПАРТ } } } then 5 } // попросил передать управление станции. // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ДАТ } } } then 5 } // ЕСТЬ могут обычно только одушевленные: // Антонио ест суп и пюре // ^^^^^^^ ^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:есть{}.{ <SUBJECT>ОдушОбъект{} <OBJECT>*:*{ падеж:вин } } } then 1 } /* // есть несколько возможных вариантов. tree_scorer language=Russian { if context { rus_verbs:быть{}.наречие:несколько{}.существительное:*{} } then 1 } */ // Мы можем использовать эти сюжеты в молитвах. // ^^^^^^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:использовать{}.предлог:в{}.*:*{ падеж:предл } } then 2 } // ЛУЧШЕ+инфинитив является очень частотным паттерном, в отличие от использования ЛУЧШЕ в качестве // простого атрибута глагола (как в СТАРАЙСЯ ЛУЧШЕ!) // лучше избавиться от обезьяны // ^^^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:лучше{1}.инфинитив:*{2} } then 2 } // ПОКОРМИТЬ можно кого-то одушевленного: // Мы покормили белок. // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:покормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:кормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:накормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } // СЛУШАТЬСЯ кого-то/вин: // слушаться родителей tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } // ПОЛОЖИТЬ кого-то/вин/: // Нам придётся положить его в больницу. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:положить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ложить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } // ХОТЕТЬ кому-то одуш // хочу кофе tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // КАК обычно является наречием, модифицирующим глаголы и инфинитивы // однако как остановить профессора? // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 } tree_scorer ВалентностьГлагола language=Russian generic { if context { безлич_глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 } // кроме того, КАК может атрибутировать наречия: tree_scorer language=Russian { if context { наречие:*{ степень:атриб }.<ATTRIBUTE>наречие:как{} } then 1 } // как будто они нас понимают // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 } tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как будто{} } then 7 } // внутри все выглядело как всегда // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 } tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как всегда{} } then 7 } // сегодня все было как обычно // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 } tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как обычно{} } then 7 } /* // наречие КАК обычно не стоит справа от глагола в одиночку. // убью как собаку. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{1}.<ATTRIBUTE>наречие:как{2}.[not]*:*{} } then -10 } */ // Олег вытянул вперед руки // ^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } // теперь она могла его толком рассмотреть. // ^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:толком{} } then 2 } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:толком{} } then 2 } // они быстро пересекли плато // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересечь{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересекать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } // Как вызвать такси? // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>*:*{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>*:*{ падеж:вин } } then 1 } // наверху их охватил морской ветер. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:охватить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Чиновник уже пообещал, что не будет покрывать своего родственника // ^^^^^^^^^ ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:покрывать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // Толстые линии показывают связи между участками коры // ^^^^^^^^^^ ~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 2 } // Олег хмуро окинул взглядом убитого. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окинуть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // по левой стороне груди текла кровь. // ~~~~~ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:течь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 } // это может лишить наше общество работы // ^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 } // сбивая их сильной струей воды с надводной растительности // ^^^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // Лидеры организации хасидов заявили, что деньги их не интересуют // ^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // как радостно за руку ее схватили! // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватать{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 } // Антон поднес ладони к горлу // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подносить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // оставшиеся вынуждены по очереди помогать ей двигаться вперед // ^^^^^^^^^ ^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:вынужденный{}.инфинитив:*{} } then 2 } // Артур погладил по носу старого коня // ^^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:погладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:гладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // ты можешь нас туда провести? // ^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провести{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 1 } // провожают обычно одушевленные объекты, tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 } // у ворот всадников проводили жесткие темные глаза стражи tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } // но это мешало им // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:мешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:препятствовать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } // его можно предотвратить // ^^^ ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 } // им хорошо платят // ^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } // Гарри взял tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } } then -1 } // сигареты у него забрали tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забрать{}.<SUBJECT>НеодушОбъект } then -1 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:брать{}.<SUBJECT>НеодушОбъект } then -1 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забирать{}.<SUBJECT>НеодушОбъект } then -1 } // тот принял ее мертвой рукой. // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принять{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принимать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // В США миллионера осудили за попытку продать Ирану детали для ракет ПВО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осудить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осуждать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // Африканский союз позвал войска НАТО в Мали // ^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позвать{}.предлог:в{}.*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:звать{}.предлог:в{}.*:*{ падеж:вин } } then 2 } // вряд ли это им понравится. // ^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:понравиться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } // слушайся меня // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 } // все это ее непосредственно касалось. // ^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:касаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 } // а громадный глаз подмигнул им // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигнуть{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигивать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } // ты мог бы им помочь. // ^^ ^^^^^^ //tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } //tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 } // воины окружили их кольцом. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 } // кому теперь нужны новые программы? // ^^^^ ^^^^^ tree_scorer language=Russian { if context { прилагательное:нужный{}.<OBJECT>местоим_сущ:кто{ ПАДЕЖ:ДАТ } } then 2 } // именно твое мнение для нас крайне важно. // ^^^ ^^^^^ tree_scorer language=Russian { if context { прилагательное:важный{}.предлог:для{} } then 2 } // от него ждали реакции. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } предлог:от{} } } then 2 } // протер от пыли глаза. // ^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протереть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:притирать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 } // ты предпочел камни моей жизни. // предпочесть ЧТО-ТО ЧЕМУ-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предпочесть{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предпочитать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 2 } // мы вынуждены просить вашей помощи. // ^^^^^^^ ~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:просить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запросить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // Наречие ТАК обычно не модифицирует наречия места и времени: // так где ты был? tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МЕСТО }.наречие:так{} } then -100 } tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ }.наречие:так{} } then -100 } tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ_ОТКУДА }.наречие:так{} } then -100 } tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ }.наречие:так{} } then -100 } tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:КРАТНОСТЬ }.наречие:так{} } then -100 } // равнина напоминала поле битвы. // ^^^^^^^^^^ ~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напоминать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напомнить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // Дети угостили белок орешками. // УГОСТИТЬ можно КОГО-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // хочешь кофе? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.<OBJECT>существительное:*{ падеж:род <в_класс>существительное:напиток{} } } then 1 } // мы встретили охотника, способного догнать и поймать кенгуру // ^^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поймать{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ловить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // протестующие начали собираться на площади // ^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:собираться{}.предлог:на{}.*:*{ падеж:предл } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:собраться{}.предлог:на{}.*:*{ падеж:предл } } then 1 } // Когда он вошел, все стаканы попадали с полки. // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:падать{}.предлог:с{}.*:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попадать{}.предлог:с{}.*:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:упасть{}.предлог:с{}.*:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:свалиться{}.предлог:с{}.*:*{ падеж:род } } then 2 } // подруга Иды не пришла на урок // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.предлог:на{}.*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.предлог:на{}.*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приходить{}.предлог:на{}.*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.предлог:на{}.*:*{ падеж:вин } } then 2 } // Английская традиция акварели оказала сильное влияние на русских художников // ~~~~~~~~ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказывать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 } // одна из женщин показалась ему знакомой. // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // две женщины вывели из темноты раненого. // ^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вывести{}.*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выводить{}.*:*{ падеж:вин } } then 2 } // она часто просила меня рассказывать истории. // ^^^^^^^^^^^^ ~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // Мы рассказывали о тех, кто менял мир // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказывать{}.предлог:о{}.*:*{ падеж:вин } } then -10 } // к вечеру жара спала. // ^^^^ ~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:спать{}.<SUBJECT>НеодушОбъект } then -2 } // Доллар снова сдает позиции // ^^^^^ ~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // жена полковника смотрела им вслед // ^^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.послелог:вслед{} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посмотреть{}.послелог:вслед{} } then 2 } // можно попытаться заменить собой стражу. // ^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменить{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменять{}.<OBJECT>*:*{ падеж:вин } } then 2 } // двое крестьян схватили за руки своего господина. // ^^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // тебя вызывает начальник станции. // ^^^^^^^^ ~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // тот молча сунул ей два факела. // ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сунуть{}.<OBJECT>*:*{ падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:совать{}.<OBJECT>*:*{ падеж:дат } } then 2 } // Михаил зажал себе ладонью рот. // ^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажать{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажимать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // им оставалось преодолеть около тридцати футов. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { 'оставалось'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { 'остается'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 } // ей приходилось идти очень медленно. // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { 'приходилось'{ 2 class:безлич_глагол }.<OBJECT>*:*{ 1 падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { 'приходится'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 } // кого интересует мнение машины? // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // Газета сообщает об открытии сессии парламента. // ^^^^^^^^ ~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // ей довелось увидеть только последствия. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { 'довелось'{2}.<OBJECT>*:*{ 1 падеж:дат } } then 2 } // Геолог недавно открыл залежи руды. // ^^^^^^ ~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открыть{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открывать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Дети не дают матери покоя. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:давать{}.{ частица:не{} <OBJECT>*:*{ падеж:дат } <OBJECT>*:*{ падеж:род } } } then 2 } // Директор заявил, что уходит на пенсию. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заявить{}.союз:что{} } then 2 } // Люди провозгласили его гениальным писателем. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозгласить{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозглашать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // они создали магию крови. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // они боятся меня теперь. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // они называли ее железной. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } } then 2 } // он отнес коробку к дедушке tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>*:*{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // какой вес имеют эти вещи искусства? // ^^^^^ ~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:иметь{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -100 } // но прежде нам необходимо найти тело // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:необходимо{}.{ <SUBJECT>*:*{ падеж:дат } <INFINITIVE>инфинитив:*{} } } then 2 } // вы можете предоставить ему другую работу? // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // Никто из присутствующих при этом не пострадал. // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer language=Russian { if context { местоим_сущ:никто{}.предлог:из{} } then 5 } // она протянула к огню руки. // ^^^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } // почему она ему поверила? // ^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поверить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:верить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } // человек впервые показал эмоции. // ^^^^^^^ ~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // хочешь передать ему новость? // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передавать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } // они зашли за угол крепости. // ^^^^^ ~~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заходить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // ты достаточно заплатил ему? // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 } // их тоже стало меньше? // ^^ ^^^^^ tree_scorer language=Russian { if context { 'стало'.<OBJECT>*:*{ падеж:род } } then 1 } tree_scorer language=Russian { if context { 'станет'.<OBJECT>*:*{ падеж:род } } then 1 } // ему хотелось выпить все озеро. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 } // как им хочется меня убить! // ^^^^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:хочется{}.{ <SUBJECT>ОдушОбъект{ падеж:дат } инфинитив:*{} } } then 2 } // нам следует передать им это дело // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:следует{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 } // все данные у него есть. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { 'есть'{ class:глагол 2 }.предлог:у{ 1 } } then 2 } // сколько уверенности принесли они мне. // ^^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приносить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // возьмут ли меня туда? // ^^^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:брать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } // она обхватила его руками за шею. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватить{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватывать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } // один из гномов ткнул его палкой. // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ткнуть{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тыкать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 } // такое обращение может его сильно обидеть. // ^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 } // дай мне прикончить его! // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прикончить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приканчивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // теперь она может выслушать его. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // внешность этой женщины поразила его. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поражать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // ты его недавно сделал? // ^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.<OBJECT>местоимение:*{ падеж:вин } } then 2 } // не смей вовлекать его в свои делишки // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлекать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлечь{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // дилер выгодно продал акции // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } // мы выдали ему костюм // --> выдать обычно можно кому-то tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 } // я доверяю ему в этих вопросах // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 } // Она хотела побыстрее его женить tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:женить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // его избили // --> ИЗБИТЬ КОГО-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // собственные слова тут же показались верхом глупости. // ПОКАЗАТЬСЯ можно КОМУ-ТО, а не ЧЕМУ-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:казаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // мы продолжали поднимать тяжести // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднимать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // Круче не придумаешь tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придумать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // Ключевая валютная пара останется волатильной // ^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остаться{}.прилагательное:*{ падеж:дат } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставаться{}.прилагательное:*{ падеж:дат } } then -1 } // остальные были заняты тем же tree_scorer language=Russian { if context { прилагательное:занятый{ краткий }.*:*{ падеж:твор } } then 2 } // записи мы посмотрим потом // ^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посмотреть{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -1 } // целенаправленно обеспечивали его свежей продуктовой массой // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обеспечивать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // Олег потрогал его ногой tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:потрогать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // хозяин пнул его ногой tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пнуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // Иван отодвинул его рукой tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отодвинуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // слуга вновь наполнил его вином tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:наполнить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // многие горожане сочли его попыткой скрыть преступление под давлением евреев tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:счесть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // Суд признал его виновным. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:признать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // отец остановил ее жестом руки. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остановить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // молодой человек оттолкнул его взглядом! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оттолкнуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // тот ловко подхватил его левой рукой. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подхватить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // младший толкнул его ногой tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:толкнуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // капитан прикрыл ладонью глаза tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прикрыть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // Пол удивленно поднял брови. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднять{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -1 } // ты должна ненавидеть ее всей душой // ^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ненавидеть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попытаться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then -1 } // кенгуру не умеет петь песни // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:петь{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // они называли ее железной. // ^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 1 } // Ударил ли Артур копьем дракона? // тогда ударил ее кулаком по голове tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ударить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 2 } // УДАРИТЬ можно либо что-то, либо по чему-то: // тот ударил по ней кулаком tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ударить{}.{ <OBJECT>*:*{ падеж:вин } <PREPOS_ADJUNCT>предлог:по{} } } then -5 } // +++++++++++++++++++++++++++++++++++++++++++++++++= // Самый западный и самый большой полуостров Азии - Аравийский // ^^^^^^^^^^^^^ tree_scorer language=Russian { if context { прилагательное:самый{}.прилагательное:*{} } then 1 } // Даже сторонники экс-премьера не смогли поприветствовать своего кумира tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смочь{}.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{}.<OBJECT>*:*{ падеж:вин } } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смочь{}.{ <OBJECT>*:*{ падеж:род } инфинитив:*{}.<OBJECT>*:*{ падеж:вин } } } then -1 } // ресницы ее начали опускаться tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:начать{}.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } } then -1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:начать{}.{ <OBJECT>*:*{ падеж:род } инфинитив:*{} } } then -1 } // Завершаем 83-й женевский автосалон масштабным обзором новинок в лидирующих сегментах автопрома // ^^^^^^^^^ ^^^^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:завершать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 2 } /* // В День Воли белорусов призвали побороть страх и лень // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:призвать{}.{ ОдушОбъект{ падеж:вин } инфинитив:*{} } } then 5 } // РФ призывает США воздержаться от линии силового давления на Дамаск. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:призывать{}.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } } then 5 } */ // Он не произнёс ни слова. tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.{ частица:не{} существительное:*{ падеж:род }.частица:ни{} } } then 5 } // США хотят нормализовать отношения с Россией tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:хотеть{}.{ <SUBJECT>*:*{} инфинитив:*{} } } then 1 } // их стали делать // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:стать{1}.инфинитив:*{ вид:несоверш } } then 2 } // Понизим достоверность связывания ПООБЕЩАТЬ с дательным падежом слева, чтобы не // возникала ошибка в предложениях типа: // Президент Ингушетии пообещал ... tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пообещать{2}.{ <OBJECT>*:*{ 1 падеж:дат } } } then -1 } // ======================================================================== // Некоторые модальные глаголы не могут присоединять прямое дополнение в // винительном падеже, если присоединен инфинитив: // // Я ничего не смог из него выжать // ^^^^^^ ~~~~ // Я яблоко ему не смог отдать // ^^^^^^ ~~~~ wordentry_set МодальнБезДоп={ rus_verbs:советовать{}, // Общество потребителей советует аккуратно использовать банковские карты rus_verbs:рекомендовать{}, rus_verbs:мочь{}, // Комментарии можете оставить при себе rus_verbs:позволять{}, // Островное положение города позволяет смягчить колебания температур rus_verbs:требовать{}, // долг чести требовал освободить ее. rus_verbs:продолжать{}, // глаза его продолжали оставаться широко раскрытыми. rus_verbs:захотеть{}, // он споры захочет решать мечом rus_verbs:смочь{}, // ты сможешь ее удержать? rus_verbs:начинать{}, // голос ее начинал дрожать rus_verbs:принуждать{}, // Полицейских принуждают покупать лотерейные билеты rus_verbs:продолжить{}, // США продолжат распространять демократию по всему миру rus_verbs:позволить{}, // Курс нового Советского правительства на индустриализацию страны позволил создать мощную промышленную базу rus_verbs:закончить{}, // Я только что закончил писать письмо. rus_verbs:заканчивать{}, rus_verbs:начать{}, rus_verbs:пробовать{}, rus_verbs:попробовать{}, rus_verbs:дозволять{}, rus_verbs:дозволить{}, rus_verbs:разрешать{}, rus_verbs:разрешить{}, rus_verbs:запрещать{}, rus_verbs:запретить{}, rus_verbs:предписывать{}, rus_verbs:предписать{}, rus_verbs:присоветывать{}, rus_verbs:обожать{}, rus_verbs:поручать{}, rus_verbs:поручить{}, rus_verbs:предпочитать{}, rus_verbs:предпочесть{}, rus_verbs:бояться{}, rus_verbs:побояться{}, rus_verbs:бросать{}, rus_verbs:бросить{}, rus_verbs:давать{}, rus_verbs:дать{}, rus_verbs:доверять{}, rus_verbs:доверить{}, rus_verbs:желать{}, rus_verbs:хотеть{}, rus_verbs:забывать{}, rus_verbs:забыть{}, rus_verbs:задумывать{}, rus_verbs:задумать{}, rus_verbs:кончать{}, rus_verbs:кончить{}, rus_verbs:любить{}, rus_verbs:полюбить{}, rus_verbs:мешать{}, rus_verbs:помешать{}, rus_verbs:ожидать{}, rus_verbs:планировать{}, rus_verbs:запланировать{}, rus_verbs:предлагать{}, rus_verbs:предложить{}, rus_verbs:пытаться{}, rus_verbs:попытаться{}, rus_verbs:рассчитывать{}, rus_verbs:посоветовать{}, rus_verbs:потребовать{}, rus_verbs:уметь{}, rus_verbs:суметь{}, rus_verbs:успевать{}, rus_verbs:успеть{}, rus_verbs:решать{}, rus_verbs:решить{}, rus_verbs:напоминать{}, rus_verbs:напомнить{}, rus_verbs:обещать{}, rus_verbs:пообещать{}, rus_verbs:прекращать{}, rus_verbs:прекратить{}, rus_verbs:указывать{}, rus_verbs:указать{} } // Попробуй ты ее успокоить tree_scorer ВалентностьГлагола language=Russian { if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:род } инфинитив:*{} } } then -100 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:вин } } then -100 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:род } } then -100 } // ======================================================================== // =========================================================================================== // Некоторые модальные глаголы обычно требуют присоединения и прямого дополнения, и инфинитива // =========================================================================================== #define МодальнСВинДоп(v) \ #begin tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{3 }.{ <OBJECT>*:*{ падеж:вин 2 } rus_verbs:v{1} } } then 4 } #end МодальнСВинДоп(заставить) // путь заставит тебя принять это МодальнСВинДоп(заставлять) // оно заставляет меня вспоминать МодальнСВинДоп(выучить) // Он выучил меня играть в шахматы. МодальнСВинДоп(учить) МодальнСВинДоп(научить) МодальнСВинДоп(попросить) МодальнСВинДоп(просить) МодальнСВинДоп(умолять) МодальнСВинДоп(упрашивать) МодальнСВинДоп(упросить) // ========================================================== // или научились ей пользоваться tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:научиться{}.{ <OBJECT>*:*{} инфинитив:*{} } } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:научиться{}.{ <OBJECT>*:*{} инфинитив:*{} } } then -10 } // Чтобы причастие или прилагательное, прикрепленное к БЫТЬ, // было согласовано с подлежащим по роду: // // а сегодняшний день обещал быть именно таким // лето должно быть именно таким /* tree_scorer ВалентностьПредиката language=Russian generic { if context { *:*{ модальный }.{ <SUBJECT>*:*{ род:муж число:ед } инфинитив:быть{}.прилагательное:*{ род:муж число:ед } } } then 1 } tree_scorer ВалентностьПредиката language=Russian generic { if context { *:*{ модальный }.{ <SUBJECT>*:*{ род:ср число:ед } инфинитив:быть{}.прилагательное:*{ род:ср число:ед } } } then 1 } tree_scorer ВалентностьПредиката language=Russian generic { if context { *:*{ модальный }.{ <SUBJECT>*:*{ род:жен число:ед } инфинитив:быть{}.прилагательное:*{ род:жен число:ед } } } then 1 } tree_scorer ВалентностьПредиката language=Russian generic { if context { *:*{ модальный }.{ <SUBJECT>*:*{ число:мн } инфинитив:быть{}.прилагательное:*{ число:мн } } } then 1 } */ // -------------------------------------------------- // подавляем присоединение одновременно прямого дополнения и инфинитива: // Я ХОЧУ ЭТО СДЕЛАТЬ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.{ инфинитив:*{} <OBJECT>*:*{ падеж:вин } } } then -100 } // приказывать секретарше принести кофе tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приказывать{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } // руководитель приказал пилоту начать снижение tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приказать{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 10 } // посоветовал ему купить лопату tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посоветовать{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 10 } // позволять другим найти ход tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позволять{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } // позволить компьютеру найти решение tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позволять{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } // лицо незнакомца было покрыто потом tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:покрытый{}.<OBJECT>НеодушОбъект{ падеж:твор } } then 2 } // Но последний -- тот, кого называли Табююзом -- прошел через врата на Землю. // ^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 2 } // В рядах оппозиции нашли «агентов Кремля» // На обломках метеорита нашли скрюченных пришельцев tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.<OBJECT>ОдушОбъект{ падеж:род } } then -10 } // их нашли уже через час tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.<OBJECT>местоимение:я{ падеж:род } } then -10 } // Российские ученые нашли челюсти чудовища на дне ледяного озера tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:род } } then -1 } // скоро она начнет искать меня tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:искать{}.<OBJECT>ОдушОбъект{ падеж:род } } then -10 } // мне придется искать помощи tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:искать{}.<OBJECT>НеодушОбъект{ падеж:род } } then -2 } // родителям пришлось искать его в одной из соседних станиц tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:искать{}.<OBJECT>местоимение:*{ падеж:род } } then -10 } // Подавим появление императива для НАСЛАТЬ, когда к нему прикреплен В+предл // В рядах оппозиции нашли «агентов Кремля» tree_scorer ВалентностьГлагола language=Russian { if context { глагол:наслать{ наклонение:побуд }.предлог:в{}.*:*{ падеж:предл } } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:наслать{ наклонение:побуд }.предлог:на{}.*:*{ падеж:предл } } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:наслать{ наклонение:побуд }.предлог:у{} } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:наслать{ наклонение:побуд }.предлог:под{} } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:наслать{ наклонение:побуд }.предлог:над{} } then -10 } // ИНТЕРЕСОВАТЬ - обычно кого-то, а не что-то // Наравне с литературой его интересует и живопись. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>НеодушОбъект } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:род } } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 } // Модальный ХОТЕТЬ, присоединив инфинитив, уже не может // присоединять некоторые предложные дополнения: // она хотела освободиться от меня tree_scorer ВалентностьГлагола language=Russian { if context { глагол:хотеть{}.{ <INFINITIVE>*:*{} предлог:от{} } } then -100 } // Обычно КОМУ-ТО идет ОДЕЖДА. // по всему берегу шла работа tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 } // Подавим присоединение наречия КАК справа к БЫТЬ: // это было как волшебство // ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:быть{1}.наречие:как{2} } then -10 } // Для ПАХНУТЬ - либо ОТ+род, либо КТО-ТО. // а от вас слишком уж пахнет tree_scorer ВалентностьПредиката language=Russian { if context { глагол:пахнуть{ вид:несоверш }.{ <SUBJECT>*:*{} предлог:от{} } } then -100 } tree_scorer ВалентностьПредиката language=Russian { if context { глагол:пахнуть{ вид:соверш }.{ <SUBJECT>*:*{} предлог:от{} } } then -100 } // Обычно время суток не может являться именным сказуемым (вместе со связкой) // где ж ты был прошлой ночью? // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { глагол:быть{}.<RHEMA>ЧастьСуток{ ПАДЕЖ:ТВОР } } then -2 } // обычно ГОВОРЯТ КОМУ-ТО: // пару минут пытался говорить. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:говорить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 } // вещи мы забрали без шума tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:забрать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 } // их кони шли легким шагом tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 } // послушай лучше меня! tree_scorer ВалентностьГлагола language=Russian { if context { глагол:послушать{ наклонение:побуд }.{ <ATTRIBUTE>'лучше'{ class:наречие } <OBJECT>*:*{ ПАДЕЖ:ВИН } } } then 5 } // нет больше вашего дракона tree_scorer language=Russian { if context { частица:нет{}.{ <ATTRIBUTE>'больше'{ class:наречие } существительное:*{ падеж:род } } } then 5 } // обычно КЕМ-ТО не едят: // Антонио ел пюре каждый день tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:есть{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ТВОР } } then -10 } // только как это сделать? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.{ <ATTRIBUTE>наречие:как{}.[not]*:*{} <OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } } then 1 } // Мозг этих существ сходен по размерам с мозгом динозавра // ^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:сходный{}.предлог:с{}.*:*{ падеж:твор } } then 2 } // Я пришёл сюда раньше его tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.предлог:раньше{}.*:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.предлог:раньше{}.*:*{ падеж:род } } then 2 } // В США миллионера осудили за попытку продать Ирану детали для ракет ПВО // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продать{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>*:*{ падеж:вин } } } then 2 } // ты можешь отдать его своему другу. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отдать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 2 } // тратить время на пустяки tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тратить{}.{ <OBJECT>НеодушОбъект{ падеж:вин } предлог.*:*{ падеж:вин } } } then 2 } // а каким же образом о нем узнали вы? // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:узнать{}.предлог:о{}.*:*{ падеж:предл } } then 2 } // еще четверо тащили под руки своих раненых // ^^^^^^ ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тащить{}.<OBJECT>*:*{ падеж:вин } } then 2 } // некоторые из них тащили за собой платформы tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тащить{}.{ предлог:из{} предлог:за{} } } then -10 } // ты можешь узнать подробности у нее // Узнав его, они закричали tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:узнать{}.<OBJECT>*:*{ падеж:род } } then -1 } // мне бы хотелось узнать о судьбе своего кота. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:узнать{}.{ предлог:о{} <OBJECT>ОдушОбъект{ падеж:вин } } } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:узнать{}.{ предлог:об{} <OBJECT>ОдушОбъект{ падеж:вин } } } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.{ предлог:о{} <OBJECT>ОдушОбъект{ падеж:вин } } } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.{ предлог:об{} <OBJECT>ОдушОбъект{ падеж:вин } } } then -100 } // меня называли прекрасным человеком tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>*:*{ падеж:твор } } } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:назвать{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>*:*{ падеж:твор } } } then -100 } // Мы выбрали его секретарём нашей организации. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выбрать{}.{ <OBJECT>ОдушОбъект{ падеж:вин } <OBJECT>ОдушОбъект{ падеж:твор } } } then 2 } // отдал бы пару лет жизни tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:узнать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 } // Предпочитаем одушевленный объект в конструкции: // // Узнать от соседей tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:узнать{}.<PREPOS_ADJUNCT>предлог:от{}.<OBJECT>НеодушОбъект{ падеж:род } } then -2 } // Общее правило для побудительного наклонения: явный субъект не // может быть в "сослагательном наклонении", то есть иметь частицу БЫ: // // меня бы непременно нашли // ^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ наклонение:побуд }.<SUBJECT>*:*{}.частица:бы{} } then -100 } // ----------------------------------------------------------------- // Некоторые наречия не сочетаются с императивом, и это позволяет // снимать омонимию: // // где мой револьвер? // ^^^ ~~~ wordentry_set СловаНеДляИмператива= { наречие:где{}, наречие:когда{}, наречие:почему{}, наречие:зачем{}, наречие:отчего{}, местоим_сущ:кто{}, местоим_сущ:кто-то{}, местоим_сущ:что{}, местоим_сущ:что-то{} } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ наклонение:побуд }.СловаНеДляИмператива } then -10 } // ----------------------------------------------------------------- // она ждала от него совсем другого tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.наречие:совсем{} } then -100 } // теперь было совсем другое дело tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:быть{}.наречие:совсем{} } then -100 } // она могла вполне оказаться правой tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказаться{}.наречие:вполне{} } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказаться{}.наречие:совсем{} } then -100 } // Для отрицательной формы переходного глагола // подавим родительный падеж для прямого одушевленного дополнения: // Самого богатого француза не пустили в Бельгию tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }.{ частица:не{} <OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } } } then -2 } // Придавим вариант прошедшего времени для несовершенного глагола, если // есть наречие настоящего или будущего времени: // уж больно ты сейчас слаб // ^^^^^^^^^^^ wordentry_set НаречиеНастБуд=наречие:{ сейчас, завтра, послезавтра } tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:слабнуть{ ВРЕМЯ:ПРОШЕДШЕЕ }.{ НаречиеНастБуд } } then -1 } // Подавляем наречие ДОСТАТОЧНО справа от БЫТЬ: // она была достаточно влажной // есть достаточно благополучные северные территории tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:быть{}.наречие:достаточно{} } then -10 } // нам всем очень жаль тебя tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:жаль{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } } then -2 } // извивалась под его длинными усами tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:извиваться{}.предлог:под{}.*:*{ падеж:вин } } then -100 } // а результаты могли быть куда хуже // ^^^^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:мочь{1}.наречие:куда{2} } then -2 } // модальный глагол МОЧЬ обычно не присоединяет предложное дополнение: // мы можем без купюр поговорить // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:мочь{}.предлог:*{} } then -1 } // когда мне смотреть новости? // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } } then -2 } // знаешь холм позади лагеря? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.предлог:позади{} } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.предлог:впереди{} } then -2 } // шли вчера по тропинке // ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { 'шли'{ наклонение:побуд }.наречие:вчера{} } then -2 } // кругом была полная тишина // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{1}. { прилагательное:*{ ~краткий падеж:им 2 } существительное:*{ падеж:им 3 } } } then -10 } // Если ПОДОШЕЛ кому-то, то запрещаем предложное дополнение "К ЧЕМУ-ТО" // Вольф широким шагом подошел к ним tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подойти{}. { <OBJECT>*:*{ ПАДЕЖ:ДАТ } предлог:к{} } } then -100 } /* // ------------------------------------------ // некоторые связочные глаголы требуют, чтобы объект был согласован с // подлежащим по роду и числу: // Он оказался сломанным #define СвязочнГлагол(v) \ #begin tree_scorer ВалентностьГлагола language=Russian { if context { глагол:v{}. { sbj=<SUBJECT>*:*{} obj=<OBJECT>прилагательное:*{ падеж:твор } } } //constraints { НесогласСущПрил(sbj,obj) } //constraints { sbj:РОД!=obj:РОД } then -100 } #end СвязочнГлагол(оказаться) оставаться остаться оказываться стать становиться притворяться притвориться прикинуться прикидываться */ // а результаты могли быть куда хуже // ^^^^ ~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:быть{}.наречие:куда{} } then -2 } // ОКАЗАТЬСЯ надо подавлять справа любые наречия, кроме ГДЕ и КОГДА: // // Засада оказалась наполовину успешной // // все оказалось гораздо хуже tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказаться{1}.наречие:*{ 2 ~ОБСТ_ВАЛ:МЕСТО ~ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ ~СТЕПЕНЬ:СРАВН } } then -2 } // объединение их в единую работающую систему составляет сверхзадачу построения искусственного интеллекта. // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:составлять{}.{ предлог:в{}.*:*{ падеж:вин } <OBJECT>*:*{ падеж:вин } } } then -2 } wordentry_set ПритяжМестТворЗапрет=притяж_частица:{ ее, его, их } // прилагательные ЕЁ, ЕГО, ИХ обычно не употребляются в качестве дополнения // творительного падежа: // силы явно оставляли ее tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{}.<OBJECT>ПритяжМестТворЗапрет } then -5 } // вы же ее давно знаете! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.<OBJECT>местоимение:я{ падеж:род } } then -2 } // вы делаете из мухи слона tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:делать{1}.{ предлог:из{2} <OBJECT>*:*{ 3 падеж:вин } } } then 1 } // Британец, спасший от акулы детей в Австралии, потерял работу (СПАСШИЙ ОТ КОГО-ТО КОГО-ТО) tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спасти{1}.{ предлог:от{2} <OBJECT>*:*{ 3 падеж:вин } } } then 1 } // небольшой штраф за родительное дополнение: // мы оба знали правила игры. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.<OBJECT>*:*{ падеж:род } } then -1 } // Придаточное ", ЧТО ..." конкурирует за ту же валентность, что и прямое винительное/родительное // дополнение, поэтому гасим одновременное наличие. // Маленький квадратик на линии между блоком оценки награды и блоком выбора действия показывает, что эта связь модулирует значимость действия // ~~~~~~~~ ^^^^^^^^^^^^^^^^ tree_scorers ВинРодДопГл tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:вин } } then 1 } tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:род } } then 1 } tree_scorer ВалентностьСложнСказ language=Russian generic { if context { *:*{}.{ <OBJECT>ВинРодДопГл <NEXT_CLAUSE>','.союз:что{} } } then -5 } wordentry_set Прелог_О_Об={ предлог:о{}, предлог:об{} } // Универсальный принцип: косвенное дополнение О+чем-то заполняет тот же слот, что // и вин/род дополнение: // О появлении свежей лавы свидетельствует мощная подсветка в вершинном кратере вулкана // ^^^^^^^^^^^ ~~~~~~~~~~~ tree_scorer ВалентностьСложнСказ language=Russian generic { if context { *:*{}.{ <OBJECT>ВинРодДопГл Прелог_О_Об.*:*{ падеж:предл } } } then -10 } // их даже стали из бумаги делать tree_scorer ВалентностьСложнСказ language=Russian { if context { rus_verbs:делать{}.{ <OBJECT>ВинРодДопГл предлог:из{} } } then 1 } // только пустое пространство - космос tree_scorer ВалентностьСложнСказ language=Russian generic { if context { '-'.<ATTRIBUTE>наречие:только{} } then -2 } // Подавим присоединение одушевленного родительного дополнения // к глаголам в случае, если глагол может присоединить винительное: // Я хочу тебя // ^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{ переходность:переходный падеж:вин падеж:род }. ОдушОбъект{ падеж:род } } then -1 } // Дмитрий сказал ей об этом tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сказать{}.<OBJECT>местоимение:я{ падеж:твор } } then -2 } // пожелать спортсменам удачи // ^^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } } then 1 } // пожелать спортсменам удачи // ^^^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } } then 1 } // желать спортсменам удачи // ^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } } then 1 } // желать спортсменам удачи // ^^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } } then 1 } // Мама налила чай // ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:налить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } } then 1 } // Оля съела пюре tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:съесть{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:еда{} } } then 1 } // испросить разрешения // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:испросить{}.<OBJECT>*:*{ падеж:род одуш:неодуш } } then 3 } // наделать в решении ошибок // ^^^^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:наделать{}.<OBJECT>существительное:*{ падеж:род } } then 2 } // дракон смотрит вслед человеку. // ^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.предлог:вслед{}.*:*{ падеж:дат } } then 1 } // нажимать на все кнопки // ^^^^^^^^ ^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:нажимать{}.предлог:на{}.существительное:*{ одуш:неодуш падеж:вин } } then 1 } // предикатив МОЖНО обычно присоединяет только одушевленный дательный агенс: // на этой удивительно четкой фотографии можно увидеть рассеянное скопление // ~~~~~~~~~~ ^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:можно{}.<SUBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 } // поэтому - очень легкий спуск tree_scorer ВалентностьПредиката language=Russian { if context { '-'.<ATTRIBUTE>наречие:очень{} } then -10 } tree_scorer ВалентностьПредиката language=Russian { if context { '–'.<ATTRIBUTE>наречие:очень{} } then -10 } tree_scorer ВалентностьПредиката language=Russian { if context { '—'.<ATTRIBUTE>наречие:очень{} } then -10 } // Мужчина, взявший в заложники пожарных в США, убит при штурме // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьСложнСказ language=Russian { if context { rus_verbs:взять{}.{ <OBJECT>*:*{ падеж:вин } предлог:в{}.*:*{ падеж:им } } } then 2 } // отчего же получается такая разница? tree_scorer ВалентностьСложнСказ language=Russian { if context { глагол:получаться{1}.{ прилагательное:*{2 падеж:им } <SUBJECT>*:*{ 3 } } } then -2 } // отчего же получилась такая разница? tree_scorer ВалентностьСложнСказ language=Russian { if context { глагол:получиться{1}.{ прилагательное:*{2 падеж:им } <SUBJECT>*:*{ 3 } } } then -2 } // черный кожаный костюм делал его почти невидимым tree_scorer ВалентностьСложнСказ language=Russian { if context { rus_verbs:делать{}.{ <OBJECT>*:*{ падеж:вин } прилагательное:*{ падеж:твор } } } then 1 } // Общее правило для глаголов - два наречия подряд прикрепляются // достаточно редко. tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.@sequence_pos(НАРЕЧИЕ) } then -1 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.@sequence_pos(НАРЕЧИЕ) } then -1 } tree_scorer ВалентностьГлагола language=Russian generic { if context { деепричастие:*{}.@sequence_pos(НАРЕЧИЕ) } then -1 } // как это все объяснить? // ^^^^^^^^^^^ tree_scorer language=Russian generic { if context { наречие:как{1}.местоим_сущ:все{} } then -1 } tree_scorer language=Russian { if context { наречие:как{1}.местоим_сущ:это{} } then -1 } // ******************************************************************************* // Подавляем одновременное присоединение винительного и родительного дополнения // // я буду ждать результаты проверки // ^^^^^^^^^^^^^^^^^^^^^^^^^ // ******************************************************************************* tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:род } } } then -10 } tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:парт } } } then -10 } tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{}.{ <OBJECT>*:*{ падеж:род } <OBJECT>*:*{ падеж:парт } } } then -10 } // ------------------------------------------------------ // Немного придавим использование прилагательного в роли // творительного дополнения: // нога жреца коснулась первой ступеньки. // ^^^^^^ wordentry_set ГлаголыСвязки= { rus_verbs:остаться{}, // вроде бы их количество осталось прежним. rus_verbs:оставить{}, // дверь туда оставим открытой. rus_verbs:оставлять{}, rus_verbs:оставаться{}, rus_verbs:становиться{}, rus_verbs:стать{}, rus_verbs:представляться{}, // оно всегда представлялось ей пронзительно голубым. rus_verbs:притвориться{}, rus_verbs:притворяться{}, rus_verbs:прикинуться{}, rus_verbs:прикидываться{}, rus_verbs:делаться{}, rus_verbs:объявить{}, rus_verbs:объявлять{}, rus_verbs:назвать{}, rus_verbs:называть{}, rus_verbs:являться{}, rus_verbs:казаться{}, rus_verbs:оказаться{}, rus_verbs:показаться{}, rus_verbs:быть{}, rus_verbs:бывать{}, rus_verbs:найти{}, // Он был найден виновным. rus_verbs:сделаться{} } tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{ ~ГлаголыСвязки }.<OBJECT>прилагательное:*{ падеж:твор } } then -2 } // Желать вам всем удачи tree_scorer ВалентностьГлагола language=Russian generic { if context { *:*{ ~ГлаголыСвязки }.<OBJECT>местоим_сущ:всё{ падеж:твор } } then -2 } // ------------------------------------------------------ // забористый бас Константина делал его легко узнаваемым tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:делать{}.<OBJECT>прилагательное:*{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.<OBJECT>прилагательное:*{ падеж:дат } } then -2 } // ------------------------------------------------------ // злодей схватил нож и несколько раз всадил его оппоненту в спину // ^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:всадить{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН} <OBJECT>*:*{ ПАДЕЖ:ДАТ } } } then 1 } // ------------------------------------------------------ // Обычно глагол не может одновременно присоединять и винительный, // и родительный падеж, но некоторые глаголы - могут: // это может лишить наше общество работы tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } } then 12 } // ------------------------------------------------------ // она обхватила его руками за шею tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // ------------------------------------------------------ // Подавляем для модального ХОТЕТЬ присоединение дополнений, // когда присоединен инфинитив: // ты это хотел мне рассказать? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then -10 } // ------------------------------------------------------ // Однако их ярость уступила место страху tree_scorer ВалентностьСложнСказ language=Russian { if context { rus_verbs:уступить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } } then 1 } // -------------------------------------------------------------- // глагол ПОМОЧЬ обычно присоединяет дательную валентность. // мне надо им помочь tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 } // ------------------------------- // злодей схватил нож и несколько раз всадил его оппоненту в спину tree_scorer ВалентностьСложнСказ language=Russian { if context { rus_verbs:всадить{}.{ <OBJECT>НеодушОбъект{ падеж:вин } <OBJECT>ОдушОбъект{ падеж:дат } } } then 1 } // ------------------------------------ // за деревьями леса не видеть tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеть{}.{ частица:не{} <OBJECT>*:*{ падеж:род } } } then 1 } // ------------------------------------ // Подавляем компаратив наречия справа от ОКАЗАТЬСЯ, если // у глагола есть прямое дополнение: // эта задача оказалась гораздо легче первой. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказаться{}.{ наречие:*{ степень:сравн } *:*{ падеж:твор } } } then -10 } // ---------------------------------------------- // Обычно рассказывают либо ЧТО-ТО, либо о ЧЕМ-ТО // Набив рот, он попросил ее рассказать о вторжении. // ^^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказать{}.{ *:*{ падеж:вин } предлог:о{} } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказать{}.{ *:*{ падеж:род } предлог:о{} } } then -5 } // Набив рот, он попросил ее рассказать о вторжении. // ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попросить{}.{ инфинитив:*{} предлог:о{} } } then -5 } // Предприниматели ФРГ выступают за добычу сланцевого газа // ^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выступать{2}.<OBJECT>*:*{ 1 падеж:твор } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выступать{}.<OBJECT>*:*{ падеж:твор <в_класс>существительное:страна{} } } then -2 } // Обычно ВОСПОЛЬЗОВАТЬСЯ имеет заполненный слот творительного дополнения: // этим мгновением надо было воспользоваться tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:воспользоваться{}.<OBJECT>*:*{ падеж:твор } } then 2 } // откуда ее черт принес? // Откуда её ветер принёс? tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:принести{}.{ <SUBJECT>*:*{} <OBJECT>*:*{ падеж:вин } } } then 1 } // ей доводилось встречать эти существа tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:доводилось{}.{ <SUBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 3 } // Есть у нас в лесу место tree_scorer ВалентностьГлагола language=Russian { if context { 'есть'{ class:инфинитив }.предлог:у{} } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заняться{}.<OBJECT>*:*{ падеж:твор } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заниматься{}.<OBJECT>*:*{ падеж:твор } } then 1 } // Майкл способен попасть в кольцо с десятиметровой дистанции пять раз подряд tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попасть{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попадать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 } // Я спустил собаку с цепи. // ^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 } // Гоша опустил ногу со стола. // ^^^^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:опустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:опускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 } // тебе доводилось использовать силы магии против другого человека? tree_scorer ВалентностьГлагола language=Russian { if context { глагол:использовать{ вид:соверш }.предлог:против{} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:использовать{ вид:несоверш }.предлог:против{} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:использовать{ вид:соверш }.предлог:против{} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:использовать{ вид:несоверш }.предлог:против{} } then 2 } // лесом от него пахло tree_scorer ВалентностьГлагола language=Russian { if context { глагол:пахнуть{ вид:несоверш }.предлог:от{} } then 2 } // Дождь должен смыть всю пыль с листьев. // ^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смыть{}.предлог:с{}.*:*{ падеж:род} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смывать{}.предлог:с{}.*:*{ падеж:род} } then 2 } // он смел крошки со стола // ^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смести{}.предлог:с{}.*:*{ падеж:род} } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сметать{}.предлог:с{}.*:*{ падеж:род} } then 2 } // Мальчики съехали на санках с горы. // ^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:съехать{}.предлог:с{}.*:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:съезжать{}.предлог:с{}.*:*{ падеж:род } } then 2 } // Дети бросались в воду с моста // ^^^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:броситься{}.предлог:с{}.*:*{ падеж:род } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бросаться{}.предлог:с{}.*:*{ падеж:род } } then 2 } // отнестись к животным с сочуствием // ^^^^^^^^^ ^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнестись{}.предлог:с{}.*:*{ падеж:твор } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относиться{}.предлог:с{}.*:*{ падеж:твор } } then 2 } // Элис разинула от удивления рот. // ^^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 2 } // -------------------------------------- // ВЛЮБЛЯТЬСЯ В КОГО-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:влюбляться{}.предлог:в{}.*:*{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 } // -------------------------------------- // ВЛЮБИТЬСЯ В КОГО-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:влюбиться{}.предлог:в{}.*:*{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 } // -------------------------------------- // ВТЮРИТЬСЯ В КОГО-ТО tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:втюриться{}.предлог:в{}.*:*{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 } // ------------------------------------------------ // **** Глаголы перемещения с топонимами **** tree_scorers ЛюбойТопонимНеизв // для неизвестных топонимов tree_scorer ЛюбойТопонимНеизв language=Russian { if context { существительное:???{ charcasing:FirstCapitalized } } then 1 } tree_scorer ЛюбойТопонимНеизв language=Russian { if context { существительное:*{ <в_класс>существительное:страна{} } } then 1 } tree_scorer ЛюбойТопонимНеизв language=Russian { if context { существительное:*{ <в_класс>существительное:город{} } } then 1 } // +++++ // для слов типа ТАКСИ tree_scorers ЛюбойТранспорт tree_scorer ЛюбойТранспорт language=Russian { if context { существительное:*{ <в_класс>существительное:транспорт{} } } then 1 } // +++++ tree_scorers ЛюбойЧеловек tree_scorer ЛюбойЧеловек language=Russian { if context { существительное:*{ <в_класс>существительное:профессия{} } } then 1 } tree_scorer ЛюбойЧеловек language=Russian { if context { существительное:*{ <в_класс>существительное:имя{} } } then 1 } // +++++ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 } // ++++ // он уехал в Токио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // он уехал в такси tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 } // ++++ // Мы эмигрировали в США tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:эмигрировать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // ++++ // Виктор перебрался в Токио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:перебраться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // ++++ // Мафиози сбежали из Токио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбежать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // ++++ // Они едут в Токио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // мы ехали в такси tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 } // ++++ // туристы поехали в Киото tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:предл } } then -10 } // группа туристов поехала в такси tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:вин } } then -10 } // ++++ // Люси отправилась в Токио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отправиться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // ++++ // Мы посетили Киото tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посетить{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // ++++ // путешественники посещали Киото tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посещать{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 } // ++++ // Мы спросили Людмилу Ивановну tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спросить{}.ЛюбойЧеловек{ падеж:вин } } then 2 } // Дети спросили совет у учителя tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спросить{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 } // ++++ // Дети спрашивают медсестру tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спрашивать{}.ЛюбойЧеловек{ падеж:вин } } then 2 } // Дети спрашивают совет у учителя tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спрашивать{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 } // ++++ // мы поинтересовались ответом у учительницы tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поинтересоваться{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 } // ++++ // Вдалеке мы увидели Токио tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:увидеть{}.*:*{ падеж:вин } } then 1 } // ++++ // Справа вы видите Киото tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеть{}.*:*{ падеж:вин } } then 1 } // ++++ // tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:построить{}.НеодушОбъект{ падеж:вин } } then 1 } // ++++ // tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:строить{}.НеодушОбъект{ падеж:вин } } then 1 } // ++++ // tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создать{}.НеодушОбъект{ падеж:вин } } then 1 } // ++++ // tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{}.НеодушОбъект{ падеж:вин } } then 1 } // ++++ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обмениваться{}.*:*{ падеж:твор } } then 1 } // ++++ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обменяться{}.*:*{ падеж:твор } } then 1 } // +++++ // Элис разинула от удивления рот. // ^^^^^^^^ ^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 1 } // ++++++ // Я покажу тебе, как надо мной смеяться! // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смеяться{}.местоимение:*{ падеж:твор } } then -5 } // ++++++++++ // плыть ей пришлось долго. tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:пришлось{}.{ <SUBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:плыть{}.местоимение:*{ падеж:твор } } then -5 } // ++++++++++ // все остальное тебе тоже удалось устроить? tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:удалось{}.{ <SUBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } // +++++++++++++++ // Это событие является одним из элементов широко задуманной акции. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:являться{}.'одним'{ падеж:твор }.'из' } then 2 } // +++++++++++++++ // вот кого мне нужно было искать! tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:нужно{}.{ <SUBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } // +++++++++++++++++ // им надо видеть движение. tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:надо{}.{ <SUBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 2 } // +++++++++++++++++ // но прежде нам необходимо найти тело tree_scorer ВалентностьПредиката language=Russian { if context { безлич_глагол:необходимо{2}.{ <SUBJECT>*:*{ падеж:дат 1 } инфинитив:*{3} } } then 4 } // +++++++++++++++++ // мимо тебя пройти невозможно tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:пройти{}.{ наречие:мимо{} <OBJECT>*:*{ падеж:вин } } } then -10 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:пройти{}.{ наречие:мимо{} <OBJECT>*:*{ падеж:род } } } then -10 } // +++++++++++++++++ // Сегодня я буду читать дома // ^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:читать{}.{ <OBJECT>существительное:*{ <в_класс> СУЩЕСТВИТЕЛЬНОЕ:СТРОЕНИЕ{} } } } then -10 } // +++++++++++++++++ // Она ослепила его своей красотой. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:ослепить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 2 } // +++++++++++++++++++ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } } then 2 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:слышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:услышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } } then 2 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:услышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:расслышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } } then 2 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:расслышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } } then -5 } // +++++++++++++++++++++++++ /* // пища помогла мне окончательно прогнать сон tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:помочь{}.{ <SUBJECT>*:*{} <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 5 } */ // +++++++++++++++++ // Немного повысим достоверность императива в случае, // когда предложение оканчивается восклицательным знаком: // держите ее за ноги! tree_scorer language=Russian { if context { глагол:*{ наклонение:побуд }.'!' } then 1 } // - А яичницу любите? tree_scorer language=Russian { if context { глагол:*{ наклонение:побуд }.'?' } then -4 } // +++++++++++++++++ // Страх охватил Грегори tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:охватить{}.{ <SUBJECT>существительное:*{ одуш:неодуш <в_класс>существительное:эмоция{} } <OBJECT>*:*{ падеж:вин } } } then 5 } // ++++++++++++++++++ // какие тут могут быть секреты? tree_scorer ВалентностьГлагола language=Russian { if context { глагол:мочь{}.{ инфинитив:*{} <OBJECT>*:*{ падеж:вин } } } then -100 } // +++++++++++++++++ // В Ульяновской области детей обстреляли из пневматики tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обстрелять{}.<OBJECT>*:*{ падеж:вин } } then 2 } // +++++++++++++++++ // теперь вы все знаете tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.<OBJECT>'все'{ падеж:вин } } then 2 } // +++++++++++++++++ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предложить{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 6 } // +++++++++++++++++ // Мы велели ей убраться из комнаты tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:велеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then 6 } // +++++++++++++++++ // Обычно глагол БЫТЬ не присоединяет прямое дополнение в винительном падеже: // Это будет аварийный запас. tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.<OBJECT>*:*{ падеж:вин } } then -5 } // в этом кафе будут они tree_scorer ВалентностьПредиката language=Russian { if context { глагол:быть{}.{ <SUBJECT>местоимение:*{ падеж:им } <RHEMA>*:*{ одуш:неодуш падеж:им } } } then -3 } tree_scorer ВалентностьПредиката language=Russian { if context { глагол:быть{}.{ <RHEMA>местоимение:*{ падеж:им } <SUBJECT>существительное:*{ одуш:неодуш падеж:им } } } then -3 } // Компаратив наречия для БЫТЬ/БЫВАТЬ подавляем // она была старше меня tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.<RHEMA>наречие:*{ степень:сравн } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:бывать{}.<RHEMA>наречие:*{ степень:сравн } } then -5 } // +++++++++++++++++ // Глаголы, синонимичные ЗАПЕРЕТЬ - подавляем вариант, когда подлежащим становится // существительное из класса ЗДАНИЕ: // запер сарай // ^^^^^^^^^^^^ #define ЗаперетьЗдание(v) \ #begin tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } } then -100 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } } then -100 } #end ЗаперетьЗдание(запереть) ЗаперетьЗдание(запирать) ЗаперетьЗдание(закрыть) ЗаперетьЗдание(закрывать) ЗаперетьЗдание(открыть) ЗаперетьЗдание(открывать) // +++++++++++++++++ // она несла на плечах своего мужа. // ^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:нести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 1 } // +++++++++++++++++++++ // И была опасность, что когда-нибудь откажет дыхательный аппарат. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отказать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then -2 } // ++++++++++++++++++++++ // Ты знаешь, что на следующий день должен был приехать мой муж. // ^^^ ^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:должный{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } инфинитив:*{} } } then -100 } // Двое гонцов из Мурманска должны были прибыть ночным поездом. tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:должный{}.{ <OBJECT>*:*{ ПАДЕЖ:РОД } инфинитив:*{} } } then -100 } // ++++++++++++++++++++++ // чувашскими законотворцами был взят проект Федерального закона tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ КРАТКИЙ СТРАД ПРИЧАСТИЕ }.<OBJECT>*:*{ падеж:род } } then -5 } // ++++++++++++++++++++++ // ружье его было тут tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.'его'{ class:прилагательное } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.'ее'{ class:прилагательное } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.'их'{ class:прилагательное } } then -5 } // +++++++++++++++++++++++++++ // его отучают пить из-под крана tree_scorer language=Russian { if context { инфинитив:*{}. <LEFT_AUX_VERB>глагол:отучать{}. ОдушОбъект{ ПАДЕж:ВИН } } then 2 } // +++++++++++++++++++++++++++++++ // Смелость города берёт tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:брать{}.<OBJECT>существительное:*{ падеж:вин } } then 1 } // -------------------------------- // это открытие его удивило tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:удивить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 } // ++++++++++++++++++++++++++++++++++++++++++++ // Ветерок был приятным // ^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian generic { if context { глагол:быть{}.{ thema=<SUBJECT>*:*{} rhema=<RHEMA>прилагательное:*{} } } then adj_noun_score(rhema,thema) } // Выбор фруктов слаб tree_scorer ВалентностьПредиката language=Russian generic { if context { a=прилагательное:*{ КРАТКИЙ}.n=<SUBJECT>СУЩЕСТВИТЕЛЬНОЕ:*{} } then adj_noun_score(a,n) } // Воздух становился всё холоднее // ^^^^^^ ^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian generic { if context { глагол:становиться{}.{ thema=<SUBJECT>*:*{} rhema=прилагательное:*{} } } then adj_noun_score(rhema,thema) } tree_scorer ВалентностьПредиката language=Russian generic { if context { глагол:стать{}.{ thema=<SUBJECT>*:*{} rhema=прилагательное:*{} } } then adj_noun_score(rhema,thema) } // ----------------------------------- #define VerbInstr(v,w) \ #begin tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:v{}.<OBJECT>существительное:*{ падеж:твор } } then w } #end VerbInstr(ограничиться,2) VerbInstr(интересоваться,2) VerbInstr(заинтересоваться,2) VerbInstr(поинтересоваться,2) VerbInstr(пренебрегать,2) VerbInstr(пренебречь,2) VerbInstr(увенчаться,2) // ---------------------------------- // Все звали ее Верочкой... tree_scorer ВалентностьГлагола language=Russian { if context { глагол:звать{}.{ <OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } <OBJECT>существительное:*{ ПАДЕЖ:ТВОР } } } then 2 } // ---------------------------------- /* wordentry_set ПредлогНаправления = предлог:{ на, в, под, через } // дракону на спину сел tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ ~ПАДЕЖ:ДАТ }.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН } } } then 8 } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{ ~ПАДЕЖ:ДАТ }.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН } } } then 8 } */ // ----------------------------------- // Официант денег не взял. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.{ частица:не{} <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } } then 2 } // ---------------------------------- // эти последние энергично пошли им навстречу. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пойти{}.послелог:навстречу{}.*:*{ падеж:дат } } then 5 } // Он сделал шаг ей навстречу. // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } послелог:навстречу{}.*:*{ падеж:дат } } } then 5 } // --------------------------------- tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объявить{}.{ <OBJECT>*:*{ падеж:вин } предлог:о{} } } then -100 } // ---------------------------------- // именно поэтому она собиралась предложить им очень простой выбор. // ^^^^^^^^^^ ^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предложить{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>*:*{ падеж:вин } } } then 5 } // ----------------------------------------------- tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:править{}.<OBJECT>существительное:*{ <в_класс>существительное:страна{} ПАДЕЖ:ТВОР } } then 5 } // ---------------------------------- // мы уже начали за вас волноваться. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:волноваться{}.предлог:за{}.*:*{ падеж:вин } } then 5 } // ---------------------------------- // ей следовало бы проверить зрение. tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:следует{}.{ *:*{ падеж:дат } инфинитив:*{} } } then 2 } // ---------------------------------- // как легко превратить в кляксу живого человека tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:превратить{}.{ <OBJECT>*:*{ падеж:вин } предлог:в{}.*:*{ падеж:вин } } } then 2 } // ---------------------------------- // мне надо было встать tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.{ БезличСвязка0 безлич_глагол:*{ ~ТИП_ПРЕДИКАТИВ:БЫЛО_СВЯЗКА } } } then -5 } // ---------------------------------- // Уточняем согласование подлежащего и // атрибута для связочных глаголов: // wordentry_set СвязочныеГлаголы= { rus_verbs:стать{}, rus_verbs:становиться{}, rus_verbs:быть{}, rus_verbs:бывать{}, rus_verbs:оказаться{}, rus_verbs:оказываться{}, rus_verbs:получиться{}, rus_verbs:получаться{} } // Он может стать главным // ^^ ^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { СвязочныеГлаголы.{ sbj=<SUBJECT>*:*{ ЧИСЛО:ЕД } прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ !=sbj:РОД } } } then -2 } // Ты можешь стать главным // ^^ ^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { СвязочныеГлаголы.{ sbj=<SUBJECT>местоимение:я{ ЧИСЛО:ЕД ~лицо:3 } прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ РОД:СР } } } then -2 } // ---------------------------------- #define НеГлагРодЕд(v,n,w) \ #begin tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:v{}.{ частица:не{} <OBJECT>существительное:n{ падеж:род число:ед } } } then w } #end // Америка не имеет права вмешиваться во внутренние дела России // ^^^^^^^^^^^^^^ НеГлагРодЕд(иметь,право,2) // Ни один прокурор такого разрешения не даст. НеГлагРодЕд(дать,разрешение,8) // ---------------------------------- // Надежде приходилось, чтобы успеть вставить свои ответы между его репликами, произносить слова со скоростью пулеметной очереди. tree_scorer ВалентностьГлагола language=Russian { if context { безлич_глагол:приходится{}.инфинитив:*{ вид:несоверш } } then 2 } // ---------------------------------- // Мы внедрили в его организацию соглядатая tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрить{}.существительное:*{ падеж:вин } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрять{}.существительное:*{ падеж:вин } } then 1 } // ---------------------------------- // Основание качнулось, зажатое манипуляторами. // ^^^^^^^^^ ^^^^^^^ tree_scorer ВалентностьПредиката language=Russian generic { if context { глагол:*{}.{ n3=<SUBJECT>*:*{} <SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО } } } then 2 } // День выдался ненастный. tree_scorer ВалентностьПредиката language=Russian generic { if context { *:*{}.{ sbj=<SUBJECT>существительное:*{} attr=<SEPARATE_ATTR>прилагательное:*{ ПАДЕЖ:ИМ =sbj:РОД =sbj:ЧИСЛО } } } then adj_noun_score(attr,sbj) } // Такое было удовольствие! tree_scorer ВалентностьПредиката language=Russian generic { if context { глагол:быть{}.{ n3=<SUBJECT>*:*{} attr=<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО } } } then adj_noun_score(attr,n3) } // Ответы я давал самые несуразные. // ^^^^^^ ^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian generic { if context { глагол:*{}.{ n3=<OBJECT>*:*{} <SEPARATE_ATTR>*:*{ =n3:ПАДЕЖ =n3:РОД =n3:ЧИСЛО } } } then 2 } // ------------------------------------------------------------------ // Некоторые модальные редко употребляются без инфинитива: // Разве можно в такую погоду как следует настроиться на мысль о преступлении? // ^^^^^ wordentry_set МодальныеТребуютИнф= { безлич_глагол:можно{}, безлич_глагол:хочется{}, безлич_глагол:захотелось{}, глагол:мочь{}, глагол:смочь{} } tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальныеТребуютИнф } then 7 } // ------------------------------------------- // а им уже приходилось умирать вместе tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.{ <SUBJECT>местоимение:*{ падеж:дат } безлич_глагол:*{ МОДАЛЬНЫЙ } } } then 1 } // Ей вдруг захотелось закричать от разочарования. tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } безлич_глагол:*{ МОДАЛЬНЫЙ } } } then -2 } // Ей было приятно думать об этом. tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } } } then -1 } // ------------------------------------------------------ // им давно пора уходить. wordentry_set БезличнМодальн=безлич_глагол:{ пора, надо, нужно } tree_scorer ВалентностьПредиката language=Russian generic { if context { инфинитив:*{}.{ *:*{ падеж:дат } БезличнМодальн } } then 1 } // ------------------------------------------------------- // у нас мало времени! tree_scorer ВалентностьПредиката language=Russian { if context { СчетнСвязка.{ предлог:у{} существительное:время{ падеж:род } } } then 10 } // ---------------------------------------------- // ЕСЛИ не сочетается с императивом: // - Не объясняйте, если не хотите. // ^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ наклонение:побуд }.'если' } then -10 } // -------------------------------------------- // Частица НЕТ не всегда выполняет роль предикатива, иногда // она выступает в роли вводной частицы, аналогично ДА: // - Нет, вы не понимаете. // ^^^ tree_scorer ВалентностьПредиката language=Russian { if context { частица:нет{}.[not]<OBJECT>*:*{} } then -2 } // --------------------------------------------- // Позади никого не было. // ^^^^^^^^^^^^^^ // Пыли не было // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.{ частица:не{} <OBJECT>*:*{ ПАДЕЖ:РОД } } } then 4 } // Радости не было предела tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }. { частица:не{} <OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } <OBJECT>'предела'{ ПАДЕЖ:РОД } } } then 6 } // --------------------------------------------- wordentry_set ОтрицМестоим = местоим_сущ:{ никто, ничто } // Местоимение НИЧТО и НИКТО в косвенных падежах обычно прикрепляются // только к глаголу с частией НЕ: // // Стояла ничем не нарушаемая тишина. // ~~~~~~ ^^^^^ ^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.{ [not]частица:не{} <OBJECT>ОтрицМестоим{} } } then -5 } // ------------------------------------------------------- // Я имею на это право. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:иметь{}.{ <OBJECT>существительное:право{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } } } then 1 } // Они, должно быть, спустились с горы. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:спуститься{}.предлог:с{}.*:*{ падеж:вин } } then -5 } // ------------------------------------------------------------ // наконец усталость дала о себе знать. // ^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:знать{}.rus_verbs:дать{} } then 2 } // ------------------------------------------------------------ // Но никто не обращал на них внимания. // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обращать{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } } then -1 } // распространяться по территории штата tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:распространяться{}.предлог:по{}.*:*{ ПАДЕЖ:ВИН } } then -1 } // я собираюсь с тобой в прятки поиграть // ^^^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поиграть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:играть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } } then 1 } // бежать, повалявшись в снегу, обратно в тепло // ^^^^^^ ^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бежать{}.предлог:в{}.*:*{ ПАДЕЖ:ВИН ОДУШ:НЕОДУШ } } then 1 } // Ты сама ко мне лезла! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лезть{}.предлог:к{}.*:*{ ПАДЕЖ:ДАТ } } then 1 } // В действительности же дело обстояло не так. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} } then 1 } // Тем дело пока и кончилось. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:кончиться{}.{ <SUBJECT>существительное:дело{} <OBJECT>*:*{ ПАДЕЖ:ТВОР } } } then 1 } // На этом дело и кончилось. // ^^^^ ^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:кончиться{}.<SUBJECT>существительное:дело{} } then 1 } // В действительности же дело обстояло не так. // ^^^^ ^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} } then 1 } // Озеленение на этом не закончится. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:закончиться{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } } then 1 } // Ты что-то от меня скрываешь? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:скрывать{}.предлог:от{}.ОдушОбъект{ ПАДЕЖ:РОД } } then 1 } // мы будем атаковать // ^^^^^^^^^^^^^^^ tree_scorer ГлагИнф language=Russian generic { if context { инфинитив:*{ ВИД:СОВЕРШ }.МодальныеТолькоНесоверш } then -100 } // Ужин был подан, и все сели за стол. // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сесть{}.предлог:за{}.существительное:стол{} } then 1 } // Ты совсем отстал от жизни. // ^^^^^^ ^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отстать{}.предлог:от{} } then 2 } // Тут есть над чем задуматься // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:задуматься{}.предлог:над{} } then 2 } // Пора было положить этому конец. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:положить{}.{ <OBJECT>существительное:конец{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ДАТ } } } then 2 } // Задержать преступников по горячим следам милиционерам не удалось. // ^^^^^^^^^ ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:задержать{}."по"."горячим"."следам" } then 4 } // ---------------------------- // Особо обрабатываем ситуацию с появлением РОДИТЕЛЬНОЙ валентности в случае, // когда модальный глагол стоит в отрицательной форме: // // Ломать вы ничего не хотите. // ^^^^^^ ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН } .{ <LEFT_AUX_VERB>глагол:*{}.<NEGATION_PARTICLE>частица:не{} <OBJECT>*:*{ ПАДЕЖ:РОД } } } then 3 } // ---------------------------------------- // Они не хотят ее знать. tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:знать{}.{ <LEFT_AUX_VERB>глагол:хотеть{} } } then 5 } // Никому до тебя нет дела tree_scorer ВалентностьПредиката language=Russian { if context { частица:нет{}.{ <OBJECT>'дела'{ падеж:род } <PREPOS_ADJUNCT>предлог:до{} } } then 5 } // Я не удостоил Ее ответом. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <OBJECT>'ответом' } } then 2 } // ----------------------------------------------- // Горю родителей нет предела. tree_scorer ВалентностьПредиката language=Russian { if context { частица:нет{}.{ <OBJECT>'предела'{ падеж:род } *:*{ ПАДЕЖ:ДАТ } } } then 5 } // ----------------------------------------- // Он весь день провел со мной! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провести{}.{ <OBJECT>'день'.'весь' <PREPOS_ADJUNCT>предлог:с{}.*:*{ падеж:твор } } } then 4 } // Рабочие день и ночь трудятся. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:трудиться{}.<ATTRIBUTE>'день'.'и'.'ночь' } then 2 } wordentry_set СчетныеНаречия=наречие:{ мало, немало, много, немного, маловато, многовато } // Но и этого будет мало. // ^^^^^^^^^^^^^^^^ // Контрпример: // Несколько мгновений все было тихо. // ~~~~~~~~~ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:род } <ATTRIBUTE>СчетныеНаречия } } then 5 } // Шуму было много, однако гора родила мышь. // ^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:парт } <ATTRIBUTE>СчетныеНаречия } } then 5 } // Я не удостоил Ее ответом. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'ответом' } } then 2 } word_set ЕеЕгоИхОбъект = { 'ее', 'его', 'их' } // Аня неумело стиснула ее зубами. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН ~ПАДЕЖ:ТВОР }. { <OBJECT>ЕеЕгоИхОбъект{ падеж:вин } <OBJECT>*:*{ падеж:твор } } } then 2 } // Орлиц в поле зрения не оказалось. // ^^^^^^^^^^^^^ ^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian generic { if context { rus_verbs:оказаться{}.<PREPOS_ADJUNCT>предлог:в{}.'поле'{ РОД:СР ПАДЕЖ:ПРЕДЛ }.'зрения' } then 2 } // Я пересекла двор и села рядом с ней. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сесть{}.<PREPOS_ADJUNCT>предлог:с{}.<ATTRIBUTE>наречие:рядом{} } then 2 } // Я всегда стою, обучая кого-то. // ^^ ^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:стоить{}.<SUBJECT>местоимение:я{ лицо:1 } } then -2 } // Окончив первый, принялся за второй. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приняться{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } } then -2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приниматься{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } } then -2 } // Оставшихся в живых они же заперли в резервациях. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' } then 2 } // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. // ^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разбирать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } } then 2 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разобрать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } } then 2 } // Белолобый неприязненно смерил его взглядом. // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смерить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'взглядом' } } then 2 } // Безмерно нибелунги о Зигфриде грустили. // ^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:грустить{}.<PREPOS_ADJUNCT>предлог:о{}.<OBJECT>*:*{ падеж:предл } } then 1 } // Блондин потащил девчонку к двери; // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:потащить{}.<PREPOS_ADJUNCT>предлог:к{} } then 1 } // Сняв шляпу, Рэнналф прибавил шагу. // ^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прибавить{}.<OBJECT>'шагу'{ падеж:парт } } then 3 } // Хвалю я ее за это? // ^^^^^ ^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хвалить{}.<PREPOS_ADJUNCT>предлог:за{}.<OBJECT>*:*{ падеж:вин } } then 2 } // Александр улыбнулся, пожирая её глазами. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пожирать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'глазами' } } then 2 } // мне будет сорок один год tree_scorer ВалентностьПредиката language=Russian { if context { глагол:быть{ число:ед лицо:3 время:будущее }. { <SUBJECT>существительное:год{}.числительное:*{} <OBJECT>*:*{ падеж:дат } } } then 2 } // Мне было двадцать три года. tree_scorer ВалентностьПредиката language=Russian { if context { глагол:быть{ число:ед род:ср время:прошедшее }. { <SUBJECT>существительное:год{}.числительное:*{} <OBJECT>*:*{ падеж:дат } } } then 2 } // Устойчивый оборот: принять участие в чем-то: // // В экспедиции приняли участие много иностранцев. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принять{}.{ <OBJECT>существительное:участие{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:в{}.*:*{ падеж:предл } } } then 1 } // Женщина и ребенок с ног валились. // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:валиться{}.'с'.'ног' } then 2 } // Ведет оседлый и полуоседлый образ жизни. // ^^^^^ ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вести{}.<OBJECT>'образ'.'жизни' } then 2 } // Я обещался в точности исполнить поручение. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:исполнить{}.'в'.'точности'{ падеж:предл } } then 2 } // Впрочем, может быть и меньше. // ~~~~~~ tree_scorer ВалентностьПредиката language=Russian { if context { СчетнСвязка.[not]<OBJECT>*:*{} } then -3 } // Проехали километра два. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:проехать{}.<OBJECT>существительное:километр{} } then 4 } // Прошли пять километров tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пройти{}.<OBJECT>существительное:километр{} } then 4 } // Пройдет много лет. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пройти{}.<SUBJECT>'лет'.'много' } then 4 } // Ничего не видит. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:видеть{}.<SUBJECT>'ничего' } then -4 } // Ничего не знает. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:знать{}.<SUBJECT>'ничего' } then -4 } // Ничего не боится. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:бояться{}.<SUBJECT>'ничего' } then -4 } // Взяли в клещи. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.'в'.'клещи'{ ПАДЕЖ:ВИН} } then 2 } // К вам пришли! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.'к'.*:*{ ПАДЕЖ:ДАТ } } then 1 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.'к'.*:*{ ПАДЕЖ:ДАТ } } then 1 } // Сергиенко воспользовался моментом. // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:воспользоваться{}.[not]<OBJECT>*:*{ ПАДЕЖ:ТВОР } } then -1 } // Готовиться времени нет. tree_scorer ВалентностьПредиката language=Russian { if context { частица:нет{}.'времени'.<INFINITIVE>инфинитив:*{} } then 4 } // Дал время подумать. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:дать{}.<OBJECT>существительное:время{ падеж:вин }.<INFINITIVE>инфинитив:*{} } then 4 } // ------------------------------------------------------------------------------- // Ночь выдается беспокойная. // ^^^^^^^^^^^^^ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:выдаваться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } } then 4 } tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:выдаться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } } then 4 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдаваться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} } then -10 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдаться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} } then -10 } // ------------------------------------------------------------------------------- // Что говорит свинец? tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:говорить{}.<SUBJECT>местоим_сущ:что{} } then -3 } // В детях эта программа усиливается во много раз. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:усиливаться{}."во"."раз"."много" } then 5 } // Я посмотрел на часы. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посмотреть{}."на".*{ ПАДЕЖ:ВИН } } then 3 } // К вам пришли! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}."к".ОдушОбъект } then 3 } // Он бросил взгляд на часы. (БРОСИТЬ ВЗГЛЯД НА что-то) tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бросить{}.{ <OBJECT>"взгляд"{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>"на".*:*{ ПАДЕЖ:ВИН } } } then 3 } // Женщина и ребенок с ног валились. (ВАЛИТЬСЯ С НОГ) // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:валиться{}."с"."ног" } then 3 } // стыдно ребятам в глаза смотреть. (СМОТРЕТЬ В ГЛАЗА) tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}."в"."глаза"{ ПАДЕЖ:ВИН } } then 3 } // Надежнее иметь дело со взрослыми. (ИМЕТЬ ДЕЛО С кем-то/чем-то) // ^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:иметь{}.{ <OBJECT>существительное:дело{ падеж:вин } <PREPOS_ADJUNCT>предлог:с{}.*:*{ ПАДЕЖ:ТВОР } } } then 3 } // Вдохновлял он ее и на поэмы. (ВДОХНОВЛЯТЬ/ВДОХНОВИТЬ НА что-то) // ^^^^^^^^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вдохновлять{}.<PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } } then 3 } // Оставшихся в живых они же заперли в резервациях. (ОСТАТЬСЯ В ЖИВЫХ) // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' } then 3 } // Я стояла, провожая его взглядом. (ПРОВОЖАТЬ кого-то/что-то ВЗГЛЯДОМ) // ^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провожать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'взглядом' } } then 3 } // Эпидемии гриппа не ожидается tree_scorer ВалентностьГлагола language=Russian { if context { "ожидается".{ <OBJECT>*:*{ ПАДЕЖ:РОД } 'не' } } then 3 } // -------------------------------------------------------------------------- // Прикажи дать коньяку. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}.<OBJECT>*:*{ ПАДЕЖ:ПАРТ <в_класс>СУЩЕСТВИТЕЛЬНОЕ:НАПИТОК{} } } then 6 } // Там дела важнее. // ^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { 'дела'.<ATTRIBUTE>НАРЕЧИЕ:*{ СТЕПЕНЬ:СРАВН } } then -10 } // -------------------------------------------------------------------- // Что делает Танасчишин? // ~~~~~~~~~~ tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:делать{}.<SUBJECT>местоим_сущ:что{} } then -3 } // ------------------------------------------------------- // Нельзя допустить атрофии. tree_scorer ВалентностьПредиката language=Russian { if context { инфинитив:допустить{}.{ <LEFT_AUX_VERB>безлич_глагол:Нельзя{} <OBJECT>*:*{ падеж:род } } } then 3 } // -------------------------------------------------------- // Надо Дорошенко сказать. // ^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ТВОР } } then -5 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ВИН } } then -5 } // -------------------------------------------------------------- // Тем не менее досталось всем. // ^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:достаться{}.<ATTRIBUTE>'всем'{ ПАДЕЖ:ТВОР } } then -20 } // Наконец достигли вершины. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:достичь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 3 } // -------------------------------------------------------------- // Возглавляет его мэр. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:возглавлять{}.[not]<OBJECT>*:*{ ПАДЕЖ:ВИН } } then -3 } tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:возглавлять{}.<OBJECT>существительное:*{ ПАДЕЖ:ВИН } } then -3 } /* // Засыпаю его вопросами. tree_scorer ВалентностьГлагола language=Russian { if context { глагол:засыпать{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ }.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'вопросами' } } then 2 } */ // Разбудила его Надя. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:разбудить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <SUBJECT>*:*{} } } then 2 } // Прошло две недели. tree_scorer ВалентностьПредиката language=Russian { if context { 'прошло'.<SUBJECT>СущСоЗначВрем{ ПАДЕЖ:РОД }.числительное:*{} } then 2 } // Я просидел дома весь день tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:просидеть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } } then 2 } // Сегодня я весь день читал. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:читать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } } then 2 } // я буду работать весь день tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:работать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } } then 2 } // вместе они шли весь день. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:идти{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } } then 2 } // бой продолжался весь день. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжаться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } } then 2 } // битва длилась весь день. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:длиться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } } then 2 } // мы играли во дворе целый день tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:играть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'целый'{ ПАДЕЖ:ВИН } } then 2 } // У меня к тебе дело // ~~~~~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:деть{ род:ср }.предлог:к{}.*:*{ падеж:дат } } then -10 } // дайте им три часа. // ^^^^^ ^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:дать{}.<OBJECT>существительное:час{}.числительное:*{} } then 5 } // Важное значение имеет и нестационарность Метагалактики. // ^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:иметь{}.<OBJECT>существительное:значение{}.'важное' } then 10 } // Я не теряю надежды. // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:терять{}.{ <NEGATION_PARTICLE>частица:не{} <OBJECT>существительное:надежда{ падеж:род число:ед } } } then 1 } // Вы не знаете Дезире? tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:знать{}.<OBJECT>существительное:*{ одуш:одуш падеж:твор } } then -5 } // Я целую Викторию... tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:целовать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } } then -5 } // Благоустройство кладбища продолжалось и летом. // ^^^^^^^^^^^^ ^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжаться{}.<ATTRIBUTE>существительное:лето{ падеж:твор } } then 5 } // ---------------------------------------------------------------- // Ей нужен был отдых. tree_scorer ВалентностьПредиката language=Russian { if context { прилагательное:нужный{ краткий }.'ей'{ падеж:твор } } then -5 } tree_scorer ВалентностьПредиката language=Russian { if context { прилагательное:нужный{ краткий }.'им'{ падеж:твор } } then -5 } // - Я тебе дам знать . tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:знать{}.rus_verbs:дать{} } then 5 } // Для отправителя они не представляли опасности. // ^^^^^^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:представлять{}.'опасности'{ ПАДЕЖ:РОД } } then 5 } // К вам это не имело отношения. // ^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { глагол:иметь{}.'отношения'{ ЧИСЛО:МН } } then -1 } // ты встала на его пути tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:встать{}.'на'.'пути'{ ПАДЕЖ:ВИН } } then -2 } // Она хотела стать моей // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.<OBJECT>существительное:стать{} } then -10 } // откуда нам это знать? tree_scorer ВалентностьПредиката language=Russian { if context { инфинитив:знать{}.{ <ATTRIBUTE>наречие:откуда{} <OBJECT>*:*{ падеж:дат } } } then 2 } // друид встал на их пути // ^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:встать{}.<PREPOS_ADJUNCT>предлог:на{}.<OBJECT>существительное:путь{ падеж:вин } } then -2 } // «Мы вытолкнули Украину из Русского мира» tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытолкнуть{}.<PREPOS_ADJUNCT>предлог:из{} } then 2 } // Владимир Путин объявил финансовые пирамиды вне закона // ^^^^^^^ ^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объявить{}.<PREPOS_ADJUNCT>предлог:вне{} } then 2 } // Содержание их было однообразно. tree_scorer ВалентностьГлагола language=Russian { if context { rhema=прилагательное:*{ КРАТКИЙ ЧИСЛО:ЕД РОД:СР }.{ thema=<SUBJECT>существительное:*{ ЧИСЛО:ЕД РОД:СР } } } then adj_noun_score(rhema,thema) } // Отдам краснохвостого сома в хорошие руки tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отдать{}.предлог:в{}.'руки'.'хорошие' } then 5 } // ---------------------------------------------------------------- // Приобретает массовый характер Стахановское движение. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приобретать{}.<OBJECT>существительное:характер{}.<ATTRIBUTE>прилагательное:массовый{} } then 5 } // Фашистские стрелки открывают ответный огонь. tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:открывать{}.{ <SUBJECT>существительное:стрелок{} <OBJECT>существительное:огонь{} } } then 5 } // Документы эти разрабатывались соответствующими начальниками. // Старый хрыч обернулся добродушным дедулей. tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>существительное:*{ падеж:твор одуш:одуш } } then -2 } // Он смотрел на танцующих вытаращенными глазами. // ^^^^^^^^^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.предлог:на{}.прилагательное:*{ падеж:предл } } then -5 } // Ей в глаза смотрела дама червей. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.{ предлог:в{} "ей"{падеж:твор} } } then -5 } // Ей даже передалось его нервное напряжение. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передаться{}."ей"{падеж:твор} } then -5 } // Ей ничего не приходило на ум. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приходить{}."ей"{падеж:твор} } then -5 } // Ей и так все было ясно. tree_scorer ВалентностьГлагола language=Russian { if context { "было"."ей"{падеж:твор} } then -5 } // Ей отвели пять часов на раздумья. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отвести{}."ей"{падеж:твор} } then -5 } // Ей смертельно надоели эти смертельные игры. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:надоесть{}."ей"{падеж:твор} } then -5 } // Ей пришлось нелегко в прошлом году. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийтись{}."ей"{падеж:твор} } then -5 } // Ей отвечали только изумленные печальные взгляды. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отвечать{}."ей"{падеж:твор} } then -5 } // Ей просто дали пипка под зад. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}."ей"{падеж:твор} } then -5 } // Ей все виделось в черном цвете. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:видеться{}."ей"{падеж:твор} } then -5 } // Ей в голову пришла одна мысль. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}."ей"{падеж:твор} } then -5 } // Ей становилось трудно даже держаться прямо; tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:становиться{}."ей"{падеж:твор} } then -5 } // Ей бы и не дали вернуться. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:дать{}."ей"{падеж:твор} } then -5 } // Ей всегда доставляло удовольствие плести интриги. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доставлять{}."ей"{падеж:твор} } then -5 } // Ей доставило немало удовольствия унизить меня. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доставить{}."ей"{падеж:твор} } then -5 } // Ей отдается вся энергия творящего артиста. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отдаваться{}."ей"{падеж:твор} } then -5 } // Ей заранее был известен результат взрыва. tree_scorer ВалентностьГлагола language=Russian { if context { прилагательное:*{краткий}."ей"{падеж:твор} } then -2 } // Ей ставят капельницы и делают уколы. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ставить{}."ей"{падеж:твор} } then -5 } // Ей вызвали «скорую помощь». tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}."ей"{падеж:твор} } then -5 } // Ей подражали все девушки Советского Союза. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подражать{}."ей"{падеж:твор} } then -5 } // Ей разрешили оформить опеку над Сашей! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:разрешить{}."ей"{падеж:твор} } then -5 } // Ей Самсонова подавай, шофера автобазы! tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подавать{}."ей"{падеж:твор} } then -5 } // Ему это с рук не сойдет. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сойти{}."с"."рук" } then 5 } tree_scorer ВалентностьГлагола language=Russian { if context { "это"."с"."рук" } then -10 } // Ему хотелось душу из нее вытрясти. // ~~~~~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { существительное:душа{}."из".местоимение:*{} } then -10 } // Ему просто не приходилось этого делать. // ^^^^^^^^^^^^ tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:делать{}."этого"{падеж:вин} } then -10 } // Ему хотелось драки, хотелось убить. tree_scorer ВалентностьГлагола language=Russian { if context { "хотелось".<OBJECT>существительное:*{число:мн падеж:вин} } then -5 } // А что со мной могло случиться? // ~~~~~~~~~~~ tree_scorer ВалентностьГлагола language=Russian { if context { "что".предлог:с{} } then -10 } // А раньше-то что молчал? // ~~~ tree_scorer ВалентностьГлагола language=Russian { if context { "молчал".<OBJECT>"что" } then -100 } tree_scorer ВалентностьГлагола language=Russian { if context { "молчал".<SUBJECT>"что" } then -100 } // А ты с ними по-русски говори. tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:говорить{}.ПРЕДЛОГ:С{}.МЕСТОИМЕНИЕ:*{ПАДЕЖ:ТВОР} } then 1 } // ---------------------------------------------------------------- #define vap(v,adv,p,w) \ #begin tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:v{}.<PREPOS_ADJUNCT>ПРЕДЛОГ:p{}.<ATTRIBUTE>НАРЕЧИЕ:adv{} } then w } #end vap(стоять,впритык,к,1) // Шкаф стоит впритык к столу. vap(стоять,вплотную,к,1) // Шкаф стоит вплотную к столу. vap(бежать,следом,за,2) // она как раз начала бежать следом за ним vap(быть,рядом,с,2) // он был рядом с дверью vap(пойти,следом,за,2) // Катя пошла следом за ними. // Я приехал в Москву одновременно с братом. // ^^^^^^^ ^^^^^^^^^^^^^^ vap(приехать,одновременно,с,1) vap(прийти,одновременно,с,1) vap(прибыть,одновременно,с,1) vap(появиться,одновременно,с,1) // Петя положил яблоки вместе с картошкой. // ^^^^^^^ ^^^^^^^^ vap(положить,вместе,с,1) vap(ложить,вместе,с,1) vap(положить,слева,от,2) // Положи книгу слева от тетради vap(глядеть,прямо,в,5) // глядя прямо в ее круглые карие глаза, произнес vap(посмотреть,прямо,в,5) vap(смотреть,прямо,в,5) vap(заглянуть,прямо,в,5) vap(швырнуть,прямо,в,5) // Он подлетает к башне и... сейчас кибер швырнет нашего гладиатора прямо в ее пустую утробу. vap(швырять,прямо,в,5) vap(кинуть,прямо,в,5) vap(кидать,прямо,в,5)
а громадный глаз подмигнул им ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигнуть{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
12,629,447
[ 1, 145, 113, 225, 145, 116, 146, 227, 145, 127, 145, 125, 145, 113, 145, 117, 145, 126, 146, 238, 145, 122, 225, 145, 116, 145, 124, 145, 113, 145, 120, 225, 145, 128, 145, 127, 145, 117, 145, 125, 145, 121, 145, 116, 145, 126, 146, 230, 145, 124, 225, 145, 121, 145, 125, 5375, 3602, 20254, 20254, 12800, 66, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3413, 67, 1017, 8922, 225, 145, 245, 145, 113, 145, 124, 145, 118, 145, 126, 146, 229, 145, 126, 145, 127, 146, 228, 146, 229, 146, 239, 145, 246, 145, 124, 145, 113, 145, 116, 145, 127, 145, 124, 145, 113, 2653, 33, 54, 5567, 2779, 288, 309, 819, 288, 436, 407, 67, 502, 2038, 30, 145, 128, 145, 127, 145, 117, 145, 125, 145, 121, 145, 116, 145, 126, 146, 230, 146, 229, 146, 239, 2916, 22782, 9422, 34, 14, 30, 14, 95, 225, 145, 258, 145, 243, 145, 247, 145, 248, 145, 249, 30, 145, 247, 145, 243, 145, 100, 289, 289, 1508, 576, 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 ]
./full_match/137/0x391128d1E106F1F90E0348F97060FCEf037cf8fa/sources/contracts/WolfRouter.sol
refund dust eth, if any
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'WolfRouter: INVALID_PATH'); amounts = WolfLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'WolfRouter: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(WolfLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); }
4,690,890
[ 1, 1734, 1074, 302, 641, 13750, 16, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7720, 1584, 44, 1290, 14332, 5157, 12, 11890, 3844, 1182, 16, 1758, 8526, 745, 892, 589, 16, 1758, 358, 16, 2254, 14096, 13, 203, 3639, 3903, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 8843, 429, 203, 3639, 3387, 12, 22097, 1369, 13, 203, 3639, 1135, 261, 11890, 8526, 3778, 30980, 13, 203, 565, 288, 203, 3639, 2583, 12, 803, 63, 20, 65, 422, 678, 1584, 44, 16, 296, 59, 355, 74, 8259, 30, 10071, 67, 4211, 8284, 203, 3639, 30980, 273, 678, 355, 74, 9313, 18, 588, 6275, 87, 382, 12, 6848, 16, 3844, 1182, 16, 589, 1769, 203, 3639, 2583, 12, 8949, 87, 63, 20, 65, 1648, 1234, 18, 1132, 16, 296, 59, 355, 74, 8259, 30, 5675, 5119, 5354, 67, 15934, 67, 2192, 51, 5321, 8284, 203, 3639, 1815, 12, 45, 59, 1584, 44, 12, 59, 1584, 44, 2934, 13866, 12, 59, 355, 74, 9313, 18, 6017, 1290, 12, 6848, 16, 589, 63, 20, 6487, 589, 63, 21, 65, 3631, 30980, 63, 20, 5717, 1769, 203, 3639, 389, 22270, 12, 8949, 87, 16, 589, 16, 358, 1769, 203, 3639, 309, 261, 3576, 18, 1132, 405, 30980, 63, 20, 5717, 12279, 2276, 18, 4626, 5912, 1584, 44, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 300, 30980, 63, 20, 19226, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xaf5969Ad7038b24f83Ae7A7A3290b5738b723dBC/sources/contractsv0.0.5/nnsregistrar/BaseRegistrarImplementation.sol
A map of expiry times
contract BaseRegistrarImplementation is Ownable,ERC721, ERC721Enumerable, ERC721URIStorage,ERC721Burnable, BaseRegistrar{ mapping(uint256=>uint) expiries; bytes4 constant private INTERFACE_META_ID = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 constant private ERC721_ID = bytes4( keccak256("balanceOf(address)") ^ keccak256("ownerOf(uint256)") ^ keccak256("approve(address,uint256)") ^ keccak256("getApproved(uint256)") ^ keccak256("setApprovalForAll(address,bool)") ^ keccak256("isApprovedForAll(address,address)") ^ keccak256("transferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256)") ^ keccak256("safeTransferFrom(address,address,uint256,bytes)") ); bytes4 constant private RECLAIM_ID = bytes4(keccak256("reclaim(uint256,address)")); string public _baseTokenURI; import {ERC721Upgradeable as ERC721} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import {ERC721EnumerableUpgradeable as ERC721Enumerable} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import {ERC721URIStorageUpgradeable as ERC721URIStorage} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import {ERC721BurnableUpgradeable as ERC721Burnable} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol"; import {IERC165Upgradeable as IERC165} from "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; function _isApprovedOrOwner(address spender, uint256 tokenId) internal view override returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function __BaseRegistrarImplementation_i(NNS _nns, bytes32 _baseNode) initializer public { __ERC721_init("NFT Name Service", "NNS"); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __ERC721Burnable_init(); __Ownable_init(); __BaseRegistrarImplementation_init(_nns,_baseNode); } function __BaseRegistrarImplementation_init(NNS _nns, bytes32 _baseNode) internal onlyInitializing { __BaseRegistrarImplementation_init_unchained( _nns, _baseNode); } function __BaseRegistrarImplementation_init_unchained(NNS _nns, bytes32 _baseNode) internal onlyInitializing { nns = _nns; baseNode = _baseNode; GRACE_PERIOD = 7 days; } function _baseURI() internal view virtual override returns (string memory) { } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } modifier live { require(nns.owner(baseNode) == address(this)); _; } modifier onlyController { require(controllers[msg.sender]); _; } function ownerOf(uint256 tokenId) public view override(IERC721, ERC721) returns (address) { require(expiries[tokenId] > block.timestamp); return super.ownerOf(tokenId); } function addController(address controller) external override onlyOwner { controllers[controller] = true; emit ControllerAdded(controller); } function removeController(address controller) external override onlyOwner { controllers[controller] = false; emit ControllerRemoved(controller); } function setResolver(address resolver) external override onlyOwner { nns.setResolver(baseNode, resolver); } function nameExpires(uint256 id) external view override returns(uint) { return expiries[id]; } function available(uint256 id) public view override returns(bool) { return expiries[id] + GRACE_PERIOD < block.timestamp; } function register(uint256 id, address owner, uint duration) external override returns(uint) { return _register(id, owner, duration, true); } function registerOnly(uint256 id, address owner, uint duration) external returns(uint) { return _register(id, owner, duration, false); } function _register(uint256 id, address owner, uint duration, bool updateRegistry) internal live onlyController returns(uint) { require(available(id)); expiries[id] = block.timestamp + duration; if(_exists(id)) { _burn(id); } _mint(owner, id); if(updateRegistry) { nns.setSubnodeOwner(baseNode, bytes32(id), owner); } emit NameRegistered(id, owner, block.timestamp + duration); return block.timestamp + duration; } function _register(uint256 id, address owner, uint duration, bool updateRegistry) internal live onlyController returns(uint) { require(available(id)); expiries[id] = block.timestamp + duration; if(_exists(id)) { _burn(id); } _mint(owner, id); if(updateRegistry) { nns.setSubnodeOwner(baseNode, bytes32(id), owner); } emit NameRegistered(id, owner, block.timestamp + duration); return block.timestamp + duration; } function _register(uint256 id, address owner, uint duration, bool updateRegistry) internal live onlyController returns(uint) { require(available(id)); expiries[id] = block.timestamp + duration; if(_exists(id)) { _burn(id); } _mint(owner, id); if(updateRegistry) { nns.setSubnodeOwner(baseNode, bytes32(id), owner); } emit NameRegistered(id, owner, block.timestamp + duration); return block.timestamp + duration; } function renew(uint256 id, uint duration) external override live onlyController returns(uint) { expiries[id] += duration; emit NameRenewed(id, expiries[id]); return expiries[id]; } function reclaim(uint256 id, address owner) external override live { require(_isApprovedOrOwner(msg.sender, id)); nns.setSubnodeOwner(baseNode, bytes32(id), owner); } function supportsInterface(bytes4 interfaceID) public override(IERC165,ERC721,ERC721Enumerable) view returns (bool) { return interfaceID == INTERFACE_META_ID || interfaceID == ERC721_ID || interfaceID == RECLAIM_ID||super.supportsInterface(interfaceID); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } }
1,930,360
[ 1, 37, 852, 434, 10839, 4124, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3360, 30855, 13621, 353, 14223, 6914, 16, 654, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 16, 4232, 39, 27, 5340, 3098, 3245, 16, 654, 39, 27, 5340, 38, 321, 429, 16, 3360, 30855, 95, 203, 565, 2874, 12, 11890, 5034, 9207, 11890, 13, 1329, 481, 606, 31, 203, 203, 565, 1731, 24, 5381, 3238, 11391, 11300, 67, 19294, 67, 734, 273, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 28064, 1358, 12, 3890, 24, 2225, 10019, 203, 565, 1731, 24, 5381, 3238, 4232, 39, 27, 5340, 67, 734, 273, 1731, 24, 12, 203, 3639, 417, 24410, 581, 5034, 2932, 12296, 951, 12, 2867, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 8443, 951, 12, 11890, 5034, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 12908, 537, 12, 2867, 16, 11890, 5034, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 588, 31639, 12, 11890, 5034, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 542, 23461, 1290, 1595, 12, 2867, 16, 6430, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 291, 31639, 1290, 1595, 12, 2867, 16, 2867, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 13866, 1265, 12, 2867, 16, 2867, 16, 11890, 5034, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 4626, 5912, 1265, 12, 2867, 16, 2867, 16, 11890, 5034, 2225, 13, 3602, 203, 3639, 417, 24410, 581, 5034, 2932, 4626, 5912, 1265, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 13, 203, 2 ]
// SPDX-License-Identifier: UNLICENSED0 pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IIdleToken.sol"; //idleLBP- idle lending borrowing pool contract ImplementIdle{ IERC20 DaiInstance; IIdleToken IdleTokenInstance; address daiAddress = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; //test erc20 token on kovan address IdleTokenAddress = 0x295CA5bC5153698162dDbcE5dF50E436a58BA21e; //IdleTokenAddress on kovan idleDai constructor(){ //instantiate Idle and Dai Token DaiInstance = IERC20(daiAddress); IdleTokenInstance = IIdleToken(IdleTokenAddress); } //@front-endDev should call approve function for this contract from token contract before calling this function function depositForLend(uint256 _amount) public payable returns(uint256){ DaiInstance.approve(address(this), _amount); DaiInstance.transferFrom(msg.sender, address(this), _amount); DaiInstance.approve(address(IdleTokenInstance), _amount); uint256 idleBalance = IdleTokenInstance.mintIdleToken(_amount, false, address(this)); return idleBalance; } //redeem funds and burn idle Tokens based on amount function redeemFunds(uint256 _amount) public returns(uint256){ uint256 redeemedToken = IdleTokenInstance.redeemIdleToken(_amount); return redeemedToken; } //check current value of idleToken function idleTokenPrice() public view returns(uint256){ uint256 price = IdleTokenInstance.tokenPrice(); return price; } //check all interest-bearing Tokens function InterestTokens() public view returns (address[] memory addresses, uint256[] memory aprs){ return IdleTokenInstance.getAPRs(); } function checkDaiBalance() public view returns(uint256){ return DaiInstance.balanceOf(msg.sender); } }
redeem funds and burn idle Tokens based on amount
function redeemFunds(uint256 _amount) public returns(uint256){ uint256 redeemedToken = IdleTokenInstance.redeemIdleToken(_amount); return redeemedToken; }
6,430,063
[ 1, 266, 24903, 284, 19156, 471, 18305, 12088, 13899, 2511, 603, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24903, 42, 19156, 12, 11890, 5034, 389, 8949, 13, 1071, 1135, 12, 11890, 5034, 15329, 203, 1377, 2254, 5034, 283, 24903, 329, 1345, 273, 28156, 1345, 1442, 18, 266, 24903, 13834, 1345, 24899, 8949, 1769, 203, 1377, 327, 283, 24903, 329, 1345, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-10 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ // function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { // require(address(this).balance >= value, "Address: insufficient balance for call"); // return _functionCallWithValue(target, data, value, errorMessage); // } function functionCallWithValue( address target, bytes memory data, uint256 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); } 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); } } } /** * @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.3._ */ 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.3._ */ 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); } } } function addressToString(address _address) internal pure returns (string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = "0"; _addr[1] = "x"; for (uint256 i = 0; i < 20; i++) { _addr[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } 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; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } /** * @dev 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); function decimals() external view returns (uint8); /** * @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 IOwnable { function policy() external view returns (address); function renounceManagement() external; function pushManagement(address newOwner_) external; function pullManagement() external; } contract Ownable is IOwnable { address internal _owner; address internal _newOwner; event OwnershipPushed( address indexed previousOwner, address indexed newOwner ); event OwnershipPulled( address indexed previousOwner, address indexed newOwner ); constructor() { _owner = msg.sender; emit OwnershipPushed(address(0), _owner); } function policy() public view override returns (address) { return _owner; } modifier onlyPolicy() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceManagement() public virtual override onlyPolicy { emit OwnershipPushed(_owner, address(0)); _owner = address(0); } function pushManagement(address newOwner_) public virtual override onlyPolicy { require( newOwner_ != address(0), "Ownable: new owner is the zero address" ); emit OwnershipPushed(_owner, newOwner_); _newOwner = newOwner_; } function pullManagement() public virtual override { require(msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled(_owner, _newOwner); _owner = _newOwner; } } interface ITreasury { function deposit( uint256 _amount, address _token, uint256 _profit ) external returns (uint256 send_); function manage(address _token, uint256 _amount) external; function valueOf(address _token, uint256 _amount) external view returns (uint256 value_); } interface ICurve3Pool { // add liquidity (frax) to receive back FRAX3CRV-f function add_liquidity( address _pool, uint256[4] memory _deposit_amounts, uint256 _min_mint_amount ) external returns (uint256); // remove liquidity (FRAX3CRV-f) to recieve back Frax function remove_liquidity_one_coin( address _pool, uint256 _burn_amount, int128 i, uint256 _min_amount ) external returns (uint256); } //main Convex contract(booster.sol) basic interface interface IConvex { function poolInfo(uint256 pid) external returns ( address lptoken, address token, address gauge, address crvRewards, address stash, bool shutdown ); //deposit into convex, receive a tokenized deposit. parameter to stake immediately function deposit( uint256 _pid, uint256 _amount, bool _stake ) external returns (bool); //burn a tokenized deposit to receive curve lp tokens back function withdraw(uint256 _pid, uint256 _amount) external returns (bool); } //sample convex reward contracts interface interface IConvexRewards { //get balance of an address function balanceOf(address _account) external returns (uint256); //withdraw to a convex tokenized deposit function withdraw(uint256 _amount, bool _claim) external returns (bool); //withdraw directly to curve LP token function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool); //claim rewards function getReward() external returns (bool); //stake a convex tokenized deposit function stake(uint256 _amount) external returns (bool); //stake a convex tokenized deposit for another address(transfering ownership) function stakeFor(address _account, uint256 _amount) external returns (bool); //get rewards for an address function earned(address _account) external view returns (uint256); } interface IAnyswapERC20 { function underlying() external view returns (address); function withdraw(uint256 amount) external returns (uint256); } interface IAnyswapRouter { function anySwapOutUnderlying( address token, address to, uint256 amount, uint256 toChainID ) external; } interface IUniswapRouter{ function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } /** * Contract deploys reserves from treasury into the Convex lending pool, * earning interest and $CVX. */ contract ConvexAllocator is Ownable { /* ======== DEPENDENCIES ======== */ using SafeERC20 for IERC20; using SafeMath for uint256; /* ======== STRUCTS ======== */ struct tokenData { address underlying; address anyswapERC20; uint256 deployed; uint256 returned; } struct rewardPid { address rewardPool; uint256 pid; } /* ======== STATE VARIABLES ======== */ IConvex public immutable booster; // Convex deposit contract //IConvexRewards public rewardPool; // Convex reward contract IAnyswapRouter public immutable anyswapRouter; // anyswap router ICurve3Pool public curve3Pool; // Curve 3Pool IUniswapRouter public router; //Uniswap router address public rewardCollector; mapping(address => tokenData) public tokenInfo; // info for deposited tokens //mapping(address => uint) public pidForReserve; // convex pid for reward pool rewardPid[] public pidForReserve; uint256 public totalValueDeployed; // total RFV deployed into lending pool uint256 public totalValueReturned; uint256 public immutable timelockInBlocks; // timelock to raise deployment limit address[] rewardTokens; uint256 public chainId = 250; uint256 public chainIdCandidate; uint256 constant INDEX_NOT_FOUND = 999999; address public ftmAddress; address public ftmAddressCandidate; uint256 public immutable ftmAddressChangeTimelock; uint256 public ftmAddressActiveblock; IERC20 DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 ANYDAI = IERC20(0x739ca6D71365a08f584c8FC4e1029045Fa8ABC4B); IERC20 CRV = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 CVX = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); /* ======== CONSTRUCTOR ======== */ constructor( address _anyswapRouter, address _booster, // address _rewardPool, address _curve3Pool, address _rewardCollector, address _ftmAddress, uint256 _ftmAddressChangeTimelock, uint256 _timelockInBlocks, address _router ) { require(_anyswapRouter != address(0)); anyswapRouter = IAnyswapRouter(_anyswapRouter); require(_booster != address(0)); booster = IConvex(_booster); // require( _rewardPool != address(0) ); // rewardPool = IConvexRewards( _rewardPool ); require(_curve3Pool != address(0)); curve3Pool = ICurve3Pool(_curve3Pool); require(_rewardCollector != address(0)); rewardCollector = _rewardCollector; timelockInBlocks = _timelockInBlocks; require(_ftmAddress != address(0)); ftmAddress = _ftmAddress; ftmAddressChangeTimelock = _ftmAddressChangeTimelock; require(_router != address(0), 'Invalid router'); router = IUniswapRouter(_router); initialize(); } /* ======== OPEN FUNCTIONS ======== */ /** * @notice claims accrued CVX rewards for all tracked crvTokens * @param stableToken address */ function harvest(address stableToken) public { //claim rewards for all crvTokens for (uint256 i = 0; i < pidForReserve.length; i++) { address rewardPool = pidForReserve[i].rewardPool; require(rewardPool != address(0), "Invalid reward pool address"); //Claim rewards IConvexRewards(rewardPool).getReward(); } uint stableAmount; for (uint256 i = 0; i < rewardTokens.length; i++) { uint256 balance = IERC20(rewardTokens[i]).balanceOf(address(this)); if (balance > 0) { //Convert rewards to stables stableAmount += swapRewardsToStable(IERC20(rewardTokens[i]), balance, IERC20(stableToken)); } } //Send stables to treasury if (stableAmount > 0) IERC20(stableToken).safeTransfer(rewardCollector, stableAmount); } /* ======== POLICY FUNCTIONS ======== */ /** * @notice withdraws asset from treasury, deposits asset into lending pool, then deposits crvToken into convex * @param token address * @param amount uint * @param amounts uint[] * @param minAmount uint * @param pid uint * @param curveToken address */ function deposit( address token, uint256 amount, uint256[4] calldata amounts, uint256 minAmount, uint256 pid, address curveToken ) public onlyPolicy { require(curve3Pool != ICurve3Pool(0), "Invalid curv3pool address"); (address _lptoken, , , address _crvRewards, , ) = booster.poolInfo(pid); require(_lptoken == curveToken, "Invalid curve token address"); //Update pidForReserve _addPidRewardItem(_crvRewards, pid); //treasury.manage( token, amount ); // retrieve amount of asset from treasury // account for deposit //uint value = treasury.valueOf( token, amount ); uint256 value = valueOf(token, amount); accountingFor(token, amount, value, true); IERC20(token).approve(address(curve3Pool), amount); // approve curve pool to spend tokens uint256 curveAmount = curve3Pool.add_liquidity( curveToken, amounts, minAmount ); // deposit into curve IERC20(curveToken).approve(address(booster), curveAmount); // approve to deposit to convex booster.deposit(pid, curveAmount, true); // deposit into convex } function valueOf(address token, uint256 amount) public view returns (uint256 value) { uint256 decimals = IERC20(token).decimals(); if (decimals > 9) { amount.div(10**(decimals - 9)); } else if (decimals < 9) { amount.mul(10**(9 - decimals)); } else { value = amount; } } /** * @notice adds Convex reward pool/pid pair * @param _rewardPool address * @param pid uint256 */ function addPidRewardItem(address _rewardPool, uint256 pid) external onlyPolicy { require(_rewardPool != address(0), "Invalid reward"); _addPidRewardItem(_rewardPool, pid); } /** * @notice removes Convex reward pool/pid pair * @param _rewardPool address * @param pid uint256 */ function removePidRewardItem(address _rewardPool, uint256 pid) external onlyPolicy { _removePidRewardItem(_rewardPool, pid); } function _addPidRewardItem(address _rewardPool, uint256 pid) internal { if (pidForReserve.length == 0) pidForReserve.push(rewardPid(_rewardPool, pid)); else { //check for duplication for (uint256 i = 0; i < pidForReserve.length; i++) { if ( pidForReserve[i].rewardPool != _rewardPool && pidForReserve[i].pid != pid ) { pidForReserve.push(rewardPid(_rewardPool, pid)); } } } } function _removePidRewardItem(address _rewardPool, uint256 pid) internal { uint256 index = INDEX_NOT_FOUND; for (uint256 i = 0; i < pidForReserve.length; i++) { if ( pidForReserve[i].rewardPool == _rewardPool && pidForReserve[i].pid == pid ) { index = i; } } //resize array if (index != INDEX_NOT_FOUND) { _removeArrayGap(index); } } function _removeArrayGap(uint256 _index) internal { require(_index < pidForReserve.length, "index out of bound"); for (uint256 i = _index; i < pidForReserve.length - 1; i++) { pidForReserve[i] = pidForReserve[i + 1]; } pidForReserve.pop(); } /** * @notice withdraws crvToken from convex, withdraws from lending pool, then deposits asset into treasury * @param token address * @param amount uint * @param minAmount uint * @param tokenIndexInPool int128 * @param pid uint * @param curveToken address */ function withdraw( address token, uint256 amount, uint256 minAmount, int128 tokenIndexInPool, uint256 pid, address curveToken ) public onlyPolicy { require(curve3Pool != ICurve3Pool(0), "Invalid curv3pool address"); (address _lptoken, , , address _crvRewards, , ) = booster.poolInfo(pid); require(_lptoken == curveToken, "Invalid curve token address"); require(_crvRewards != address(0), "Invalid reward pool address"); IConvexRewards(_crvRewards).withdrawAndUnwrap(amount, false); // withdraw to curve token IERC20(curveToken).approve(address(curve3Pool), amount); // approve 3Pool to spend curveToken curve3Pool.remove_liquidity_one_coin( curveToken, amount, tokenIndexInPool, //order of token in the Curve pool minAmount ); // withdraw from curve uint256 balance = IERC20(token).balanceOf(address(this)); // balance of asset withdrawn // account for withdrawal //uint value = treasury.valueOf( token, balance ); uint256 value = valueOf(token, balance); accountingFor(token, balance, value, false); //IERC20( token ).approve( address( treasury ), balance ); // approve to deposit asset into treasury //treasury.deposit( balance, token, value ); // deposit using value as profit so no HEC is minted IERC20(token).approve(address(anyswapRouter), balance); // approve anyswap router to spend tokens anyswapRouter.anySwapOutUnderlying( tokenInfo[token].anyswapERC20, ftmAddress, balance, chainId ); } function withdrawAnyswapERC20(address anyswapERC20Token, uint256 amount) public onlyPolicy { IAnyswapERC20(anyswapERC20Token).withdraw(amount); } function queueFtmAddress(uint256 _chainId, address _ftmAddress) external onlyPolicy { require( _ftmAddress != address(0) && _chainId != 0, "invalid chainid or address" ); ftmAddressActiveblock = block.number.add(ftmAddressChangeTimelock); ftmAddressCandidate = _ftmAddress; chainIdCandidate = _chainId; } function setFtmAddress() external onlyPolicy { require( ftmAddressCandidate != address(0) && chainIdCandidate != 0, "put new address in queue first" ); require(block.number >= ftmAddressActiveblock, "still in queue"); ftmAddress = ftmAddressCandidate; ftmAddressCandidate = address(0); chainId = chainIdCandidate; chainIdCandidate = 0; } /** * @notice sets reward collector address * @param _rewardCollector address */ function setRewardCollector(address _rewardCollector) public onlyPolicy { require( _rewardCollector != address(0) && rewardCollector != _rewardCollector, "" ); rewardCollector = _rewardCollector; } function setRouter(address _router) public onlyPolicy { require( _router != address(0) && address(router) != _router, "Invalid router address" ); router = IUniswapRouter(_router); } /** * @notice adds asset and corresponding crvToken to mapping * @param principleToken address */ function addToken(address principleToken, address anyswapERC20Token) public onlyPolicy { require(anyswapERC20Token != address(0), "invalid anyswap erc20 token"); address token = IAnyswapERC20(anyswapERC20Token).underlying(); require( token != address(0) && principleToken == token, "principle token not matched with anyswap ERC20 underlying token" ); require(tokenInfo[token].deployed <= tokenInfo[token].returned); tokenInfo[token] = tokenData({ underlying: token, anyswapERC20: anyswapERC20Token, deployed: 0, returned: 0 }); } /** * @notice add new reward token to be harvested * @param token address */ function addRewardToken(address token) public onlyPolicy { require(IERC20(token).totalSupply() > 0, "Invalid address"); require(token != address(0)); rewardTokens.push(token); } /* ======== INTERNAL FUNCTIONS ======== */ /** * @notice accounting of deposits/withdrawals of assets * @param token address * @param amount uint * @param value uint * @param add bool */ function accountingFor( address token, uint256 amount, uint256 value, bool add ) internal { if (add) { tokenInfo[token].deployed = tokenInfo[token].deployed.add(amount); // track amount allocated into pool totalValueDeployed = totalValueDeployed.add(value); // track total value allocated into pools } else { // track amount allocated into pool tokenInfo[token].returned = tokenInfo[token].returned.add(amount); // track total value allocated into pools totalValueReturned = totalValueReturned.add(value); } } /** * @notice sets up token list and rewards token */ function initialize() internal { //Initialize token list addToken(address(DAI), address(ANYDAI)); //Initialize rewards token list addRewardToken(address(CRV)); addRewardToken(address(CVX)); } /** * @notice swaps reward tokens to stable * @param rewardToken IERC20 * @param rewardAmount uint * @param _stableToken IERC20 */ function swapRewardsToStable(IERC20 rewardToken, uint rewardAmount, IERC20 _stableToken) internal returns(uint _stableAmount){ require(address(router) !=address(0), "Invalid router"); address[] memory path=new address[](2); path[0] = address(rewardToken); path[1] = address(_stableToken); uint[] memory amounts = router.getAmountsIn(rewardAmount, path); rewardToken.approve(address(router), amounts[0]); uint[] memory amountOuts = router.swapExactTokensForTokens( amounts[0], 1, path, address(this), block.timestamp ); uint amountOut = amountOuts[1]; require(_stableToken.transfer(address(this), amountOut), 'Transfer failed'); _stableAmount = amountOut; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice query all pending rewards * @return uint */ function rewardsPending() public view returns (uint256) { uint256 rewardAmount; //query all pending rewards for (uint256 i = 0; i < pidForReserve.length; i++) { address rewardPool = pidForReserve[i].rewardPool; require(rewardPool != address(0), "Invalid reward pool address"); rewardAmount += IConvexRewards(rewardPool).earned(address(this)); } return rewardAmount; } }
* @notice sets up token list and rewards token/Initialize token listInitialize rewards token list
function initialize() internal { addToken(address(DAI), address(ANYDAI)); addRewardToken(address(CRV)); addRewardToken(address(CVX)); }
10,520,045
[ 1, 4424, 731, 1147, 666, 471, 283, 6397, 1147, 19, 7520, 1147, 666, 7520, 283, 6397, 1147, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 1435, 2713, 288, 203, 3639, 527, 1345, 12, 2867, 12, 9793, 45, 3631, 1758, 12, 15409, 9793, 45, 10019, 203, 203, 3639, 527, 17631, 1060, 1345, 12, 2867, 12, 5093, 58, 10019, 203, 3639, 527, 17631, 1060, 1345, 12, 2867, 12, 22007, 60, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright (C) 2020 Christian Felde // 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.0; import "../domain/DomainManager.sol"; import "akap/contracts/IAKAP.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./ILinkedHashMap.sol"; contract LinkedHashMap is ILinkedHashMap { DomainManager public dm; IAKAP public akap; IERC721 public erc721; uint public rootPtr; uint public bodyPtr; uint public headPtr; uint public tailPtr; bool public haveBody; bool public haveHead; bool public haveTail; constructor(address _dmAddress, uint _rootPtr) public { dm = DomainManager(_dmAddress); akap = dm.akap(); erc721 = IERC721(address(akap)); rootPtr = _rootPtr; require(akap.exists(rootPtr), "LinkedHashMap: No root node"); bodyPtr = akap.hashOf(rootPtr, bytes("body")); headPtr = akap.hashOf(rootPtr, bytes("head")); tailPtr = akap.hashOf(rootPtr, bytes("tail")); } modifier onlyApproved() { require(erc721.isApprovedForAll(address(dm), msg.sender), "LinkedHashMap: Not approved for all"); _; } function ptr(uint ref) internal view returns (uint) { if (!akap.exists(ref)) return 0; return akap.seeAlso(ref); } function head() public view returns (uint) { return ptr(headPtr); } function tail() public view returns (uint) { return ptr(tailPtr); } function body() public view returns (uint) { return bodyPtr; } function setHead(uint newHead) internal { if (!haveHead) { require(dm.claim(rootPtr, bytes("head")) > 0, "LinkedHashMap: Unable to claim head"); haveHead = true; } akap.setSeeAlso(headPtr, newHead); } function setTail(uint newTail) internal { if (!haveTail) { require(dm.claim(rootPtr, bytes("tail")) > 0, "LinkedHashMap: Unable to claim tail"); haveTail = true; } akap.setSeeAlso(tailPtr, newTail); } function setNext(uint keyPtr, uint nextPtr) internal { (bytes memory value, uint prev,) = decode(akap.nodeBody(keyPtr)); akap.setNodeBody(keyPtr, encode(value, prev, nextPtr)); } function setPrev(uint keyPtr, uint prevPtr) internal { (bytes memory value,, uint next) = decode(akap.nodeBody(keyPtr)); akap.setNodeBody(keyPtr, encode(value, prevPtr, next)); } function encode(bytes memory value, uint prev, uint next) public pure returns (bytes memory entry) { return abi.encodePacked(value, prev, next); } function decode(bytes memory entry) public pure returns (bytes memory value, uint prev, uint next) { uint len = entry.length; require(len >= 0x40, "LinkedHashMap: Invalid entry length"); assembly { prev := mload(add(entry, sub(len, 0x20))) next := mload(add(entry, len)) mstore(entry, sub(len, 0x40)) } return (entry, prev, next); } function getByRef(uint ref) public view returns (bytes memory value, uint prev, uint next, uint, bool present) { if (!akap.exists(ref)) return ("", 0, 0, ref, false); bytes memory entry = akap.nodeBody(ref); if (entry.length == 0) return ("", 0, 0, ref, false); (value, prev, next) = decode(entry); return (value, prev, next, ref, true); } function get(bytes memory key) public view returns (bytes memory value, uint prev, uint next, uint ref, bool present) { return getByRef(akap.hashOf(bodyPtr, key)); } function existsByRef(uint ref) public view returns (bool present) { (,,,, present) = getByRef(ref); } function exists(bytes memory key) public view returns (bool) { return existsByRef(akap.hashOf(bodyPtr, key)); } function put(bytes memory key, bytes memory newValue) public onlyApproved() returns (bytes memory oldValue, uint prev, uint next, uint ref, bool present) { if (!haveBody) { require(dm.claim(rootPtr, bytes("body")) > 0, "LinkedHashMap: Unable to claim body"); haveBody = true; } (oldValue, prev, next, ref, present) = get(key); if (prev == 0 && next == 0) { // New entry require(dm.claim(bodyPtr, key) > 0, "LinkedHashMap: Unable to claim entry"); uint tailRef = tail(); if (tailRef == ref) { // We're updating the only entry tailRef = 0; } if (tailRef == 0) { // Empty map, set head setHead(ref); } else { // Update previous entry pointer setNext(tailRef, ref); } // Set entry akap.setNodeBody(ref, encode(newValue, tailRef, 0)); // Update tail setTail(ref); } else { // Existing entry akap.setNodeBody(ref, encode(newValue, prev, next)); } } function remove(bytes memory key) public onlyApproved() returns (bytes memory oldValue, uint prev, uint next, uint ref, bool present) { if (!haveBody) { require(dm.claim(rootPtr, bytes("body")) > 0, "LinkedHashMap: Unable to claim body"); haveBody = true; } (oldValue, prev, next, ref, present) = get(key); if (present) { if (prev != 0) { // Link next on prev to next on this entry setNext(prev, next); } else { // New first entry setHead(next); } if (next != 0) { // Link prev on next to prev on this entry setPrev(next, prev); } else { // New last entry setTail(prev); } // Clear this entry akap.setNodeBody(ref, ""); } } function isEmpty() public view returns (bool) { return head() == 0; } }
New entry We're updating the only entry Empty map, set head Update previous entry pointer
function put(bytes memory key, bytes memory newValue) public onlyApproved() returns (bytes memory oldValue, uint prev, uint next, uint ref, bool present) { if (!haveBody) { require(dm.claim(rootPtr, bytes("body")) > 0, "LinkedHashMap: Unable to claim body"); haveBody = true; } (oldValue, prev, next, ref, present) = get(key); if (prev == 0 && next == 0) { require(dm.claim(bodyPtr, key) > 0, "LinkedHashMap: Unable to claim entry"); uint tailRef = tail(); if (tailRef == ref) { tailRef = 0; } if (tailRef == 0) { setHead(ref); setNext(tailRef, ref); } } }
12,624,028
[ 1, 1908, 1241, 1660, 4565, 9702, 326, 1338, 1241, 8953, 852, 16, 444, 910, 2315, 2416, 1241, 4407, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1378, 12, 3890, 3778, 498, 16, 1731, 3778, 6129, 13, 1071, 1338, 31639, 1435, 1135, 261, 3890, 3778, 11144, 16, 2254, 2807, 16, 2254, 1024, 16, 2254, 1278, 16, 1426, 3430, 13, 288, 203, 3639, 309, 16051, 21516, 2250, 13, 288, 203, 5411, 2583, 12, 10956, 18, 14784, 12, 3085, 5263, 16, 1731, 2932, 3432, 6, 3719, 405, 374, 16, 315, 13174, 8658, 30, 18640, 358, 7516, 1417, 8863, 203, 5411, 1240, 2250, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 261, 1673, 620, 16, 2807, 16, 1024, 16, 1278, 16, 3430, 13, 273, 336, 12, 856, 1769, 203, 203, 3639, 309, 261, 10001, 422, 374, 597, 1024, 422, 374, 13, 288, 203, 5411, 2583, 12, 10956, 18, 14784, 12, 3432, 5263, 16, 498, 13, 405, 374, 16, 315, 13174, 8658, 30, 18640, 358, 7516, 1241, 8863, 203, 203, 5411, 2254, 5798, 1957, 273, 5798, 5621, 203, 203, 5411, 309, 261, 13101, 1957, 422, 1278, 13, 288, 203, 7734, 5798, 1957, 273, 374, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 13101, 1957, 422, 374, 13, 288, 203, 7734, 444, 1414, 12, 1734, 1769, 203, 7734, 27674, 12, 13101, 1957, 16, 1278, 1769, 203, 5411, 289, 203, 203, 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 ]
pragma solidity 0.4.25; /*===========================================================================================* *************************************** https://p4d.io *************************************** *============================================================================================* * * ,-.----. ,--, * \ / \ ,--.'| ,---, * | : \ ,--, | : .' .' `\ * | | .\ :,---.'| : ',---.' \ * . : |: |; : | | ;| | .`\ | * | | \ :| | : _' |: : | ' | * | : . /: : |.' || ' ' ; : * ; | |`-' | ' ' ; :' | ; . | * | | ; \ \ .'. || | : | ' * : ' | `---`: | '' : | / ; * : : : ' ; || | '` ,/ * | | : | : ;; : .' * `---'.| ' ,/ | ,.' * `---` '--' '---' * _____ _ _ _ __ __ _ _ _ * |_ _| | | | | | / _|/ _(_) (_) | | * | | | |__ ___ | | | |_ __ ___ | |_| |_ _ ___ _ __ _| | * | | | '_ \ / _ \ | | | | '_ \ / _ \| _| _| |/ __| |/ _` | | * | | | | | | __/ | |_| | | | | (_) | | | | | | (__| | (_| | | * \_/ |_| |_|\___| \___/|_| |_|\___/|_| |_| |_|\___|_|\__,_|_| * * ______ ___________ _____ _ * | ___ \____ | _ \ | ___| (_) * | |_/ / / / | | | | |____ ___ __ __ _ _ __ ___ _ ___ _ __ * | __/ \ \ | | | | __\ \/ / '_ \ / _` | '_ \/ __| |/ _ \| '_ \ * | | .___/ / |/ / | |___> <| |_) | (_| | | | \__ \ | (_) | | | | * \_| \____/|___/ \____/_/\_\ .__/ \__,_|_| |_|___/_|\___/|_| |_| * | | * |_| * _L/L * _LT/l_L_ * _LLl/L_T_lL_ * _T/L _LT|L/_|__L_|_L_ * _Ll/l_L_ _TL|_T/_L_|__T__|_l_ * _TLl/T_l|_L_ _LL|_Tl/_|__l___L__L_|L_ * _LT_L/L_|_L_l_L_ _'|_|_|T/_L_l__T _ l__|__|L_ * _Tl_L|/_|__|_|__T _LlT_|_Ll/_l_ _|__[ ]__|__|_l_L_ * ..__ _LT_l_l/|__|__l_T _T_L|_|_|l/___|__ | _l__|_ |__|_T_L_ __ * _ ___ _ _ ___ * /_\ / __\___ _ __ | |_ _ __ __ _ ___| |_ / __\_ _ * //_\\ / / / _ \| '_ \| __| '__/ _` |/ __| __| /__\// | | | * / _ \ / /__| (_) | | | | |_| | | (_| | (__| |_ / \/ \ |_| | * \_/ \_/ \____/\___/|_| |_|\__|_| \__,_|\___|\__| \_____/\__, | * ╔═╗╔═╗╦ ╔╦╗╔═╗╦ ╦ |___/ * ╚═╗║ ║║ ║║║╣ ╚╗╔╝ * ╚═╝╚═╝╩═╝────═╩╝╚═╝ ╚╝ * 0x736f6c5f646576 * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * * -> What? * The original autonomous pyramid, improved (again!): * [x] Developer optimized to include utility functions: * -> approve(): allow others to transfer on your behalf * -> approveAndCall(): callback for contracts that want to use approve() * -> transferFrom(): use your approval allowance to transfer P4D on anothers behalf * -> transferAndCall(): callback for contracts that want to use transfer() * [x] Designed to be a bridge for P3D to make the token functional for use in external contracts * [x] Masternodes are also used in P4D as well as when it buys P3D: * -> If the referrer has more than 10,000 P4D tokens, they will get 1/3 of the 10% divs * -> If the referrer also has more than 100 P3D tokens, they will be used as the ref * on the buy order to P3D and receive 1/3 of the 10% P3D divs upon purchase * [x] As this contract holds P3D, it will receive ETH dividends proportional to it's * holdings, this ETH is then distributed to all P4D token holders proportionally * [x] On top of the ETH divs from P3D, you will also receive P3D divs from buys and sells * in the P4D exchange * [x] There's a 10% div tax for buys, a 5% div tax on sells and a 0% tax on transfers * [x] No auto-transfers for dividends or subdividends, they will all be stored until * either withdraw() or reinvest() are called, this makes it easier for external * contracts to calculate how much they received upon a withdraw/reinvest * [x] Partial withdraws and reinvests for both dividends and subdividends * [x] Global name registry for all external contracts to use: * -> Names cost 0.01 ETH to register * -> Names must be unique and not already owned * -> You can set an active name out of all the ones you own * -> You can change your name at any time but still be referred by an old name * -> All ETH from registrations will be distributed to all P4D holders proportionally * */ // P3D interface interface P3D { function buy(address) external payable returns(uint256); function transfer(address, uint256) external returns(bool); function myTokens() external view returns(uint256); function balanceOf(address) external view returns(uint256); function myDividends(bool) external view returns(uint256); function withdraw() external; function calculateTokensReceived(uint256) external view returns(uint256); function stakingRequirement() external view returns(uint256); } // ERC-677 style token transfer callback interface usingP4D { function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); } // ERC-20 style approval callback interface controllingP4D { function approvalCallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract P4D { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (how many tokens it costs to hold a masternode, in case it gets crazy high later) // -> allow a contract to accept P4D tokens // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator() { require(administrators[msg.sender] || msg.sender == _dev); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier purchaseFilter(address _sender, uint256 _amountETH) { require(!isContract(_sender) || canAcceptTokens_[_sender]); if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if (onlyAmbassadors && ((totalAmbassadorQuotaSpent_ + _amountETH) <= ambassadorQuota_)) { require( // is the customer in the ambassador list? ambassadors_[_sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_sender] + _amountETH) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_sender] = SafeMath.add(ambassadorAccumulatedQuota_[_sender], _amountETH); totalAmbassadorQuotaSpent_ = SafeMath.add(totalAmbassadorQuotaSpent_, _amountETH); // execute _; } else { require(!onlyAmbassadors); _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed _customerAddress, uint256 _incomingP3D, uint256 _tokensMinted, address indexed _referredBy ); event onTokenSell( address indexed _customerAddress, uint256 _tokensBurned, uint256 _P3D_received ); event onReinvestment( address indexed _customerAddress, uint256 _P3D_reinvested, uint256 _tokensMinted ); event onSubdivsReinvestment( address indexed _customerAddress, uint256 _ETH_reinvested, uint256 _tokensMinted ); event onWithdraw( address indexed _customerAddress, uint256 _P3D_withdrawn ); event onSubdivsWithdraw( address indexed _customerAddress, uint256 _ETH_withdrawn ); event onNameRegistration( address indexed _customerAddress, string _registeredName ); // ERC-20 event Transfer( address indexed _from, address indexed _to, uint256 _tokens ); event Approval( address indexed _tokenOwner, address indexed _spender, uint256 _tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PoWH4D"; string public symbol = "P4D"; uint256 constant public decimals = 18; uint256 constant internal buyDividendFee_ = 10; // 10% dividend tax on each buy uint256 constant internal sellDividendFee_ = 5; // 5% dividend tax on each sell uint256 internal tokenPriceInitial_; // set in the constructor uint256 constant internal tokenPriceIncremental_ = 1e9; // 1/10th the incremental of P3D uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 1e22; // 10,000 P4D uint256 constant internal initialBuyLimitPerTx_ = 1 ether; uint256 constant internal initialBuyLimitCap_ = 100 ether; uint256 internal totalInputETH_ = 0; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 12 ether; uint256 internal totalAmbassadorQuotaSpent_ = 0; address internal _dev; uint256 public ACTIVATION_TIME; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal dividendsStored_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // contracts can interact with the exchange but only approved ones mapping(address => bool) public canAcceptTokens_; // ERC-20 standard mapping(address => mapping (address => uint256)) public allowed; // P3D contract reference P3D internal _P3D; // structure to handle the distribution of ETH divs paid out by the P3D contract struct P3D_dividends { uint256 balance; uint256 lastDividendPoints; } mapping(address => P3D_dividends) internal divsMap_; uint256 internal totalDividendPoints_; uint256 internal lastContractBalance_; // structure to handle the global unique name/vanity registration struct NameRegistry { uint256 activeIndex; bytes32[] registeredNames; } mapping(address => NameRegistry) internal customerNameMap_; mapping(bytes32 => address) internal globalNameMap_; uint256 constant internal nameRegistrationFee = 0.01 ether; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor(uint256 _activationTime, address _P3D_address) public { _dev = msg.sender; ACTIVATION_TIME = _activationTime; totalDividendPoints_ = 1; // non-zero value _P3D = P3D(_P3D_address); // virtualized purchase of the entire ambassador quota // calculateTokensReceived() for this contract will return how many tokens can be bought starting at 1e9 P3D per P4D // as the price increases by the incremental each time we can just multiply it out and scale it back to e18 // // this is used as the initial P3D-P4D price as it makes it fairer on other investors that aren't ambassadors uint256 _P4D_received; (, _P4D_received) = calculateTokensReceived(ambassadorQuota_); tokenPriceInitial_ = tokenPriceIncremental_ * _P4D_received / 1e18; // admins administrators[_dev] = true; // ambassadors ambassadors_[_dev] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address _referredBy) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, _referredBy); } /** * Buy with a registered name as the referrer. * If the name is unregistered, address(0x0) will be the ref */ function buyWithNameRef(string memory _nameOfReferrer) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, ownerOfName(_nameOfReferrer)); } /** * Fallback function to handle ethereum that was sent straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { if (msg.sender != address(_P3D)) { purchaseInternal(msg.sender, msg.value, address(0x0)); } // all other ETH is from the withdrawn dividends from // the P3D contract, this is distributed out via the // updateSubdivsFor() method // no more computation can be done inside this function // as when you call address.transfer(uint256), only // 2,300 gas is forwarded to this function so no variables // can be mutated with that limit // address(this).balance will represent the total amount // of ETH dividends from the P3D contract (minus the amount // that's already been withdrawn) } /** * Distribute any ETH sent to this method out to all token holders */ function donate() payable public { // nothing happens here in order to save gas // all of the ETH sent to this function will be distributed out // via the updateSubdivsFor() method // // this method is designed for external contracts that have // extra ETH that they want to evenly distribute to all // P4D token holders } /** * Allows a customer to pay for a global name on the P4D network * There's a 0.01 ETH registration fee per name * All ETH is distributed to P4D token holders via updateSubdivsFor() */ function registerName(string memory _name) payable public { address _customerAddress = msg.sender; require(!onlyAmbassadors || ambassadors_[_customerAddress]); require(bytes(_name).length > 0); require(msg.value >= nameRegistrationFee); uint256 excess = SafeMath.sub(msg.value, nameRegistrationFee); bytes32 bytesName = stringToBytes32(_name); require(globalNameMap_[bytesName] == address(0x0)); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; customerNamesInfo.registeredNames.push(bytesName); customerNamesInfo.activeIndex = customerNamesInfo.registeredNames.length - 1; globalNameMap_[bytesName] = _customerAddress; if (excess > 0) { _customerAddress.transfer(excess); } // fire event emit onNameRegistration(_customerAddress, _name); // similar to the fallback and donate functions, the ETH cost of // the name registration fee (0.01 ETH) will be distributed out // to all P4D tokens holders via the updateSubdivsFor() method } /** * Change your active name to a name that you've already purchased */ function changeActiveNameTo(string memory _name) public { address _customerAddress = msg.sender; require(_customerAddress == ownerOfName(_name)); bytes32 bytesName = stringToBytes32(_name); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; uint256 newActiveIndex = 0; for (uint256 i = 0; i < customerNamesInfo.registeredNames.length; i++) { if (bytesName == customerNamesInfo.registeredNames[i]) { newActiveIndex = i; break; } } customerNamesInfo.activeIndex = newActiveIndex; } /** * Similar to changeActiveNameTo() without the need to iterate through your name list */ function changeActiveNameIndexTo(uint256 _newActiveIndex) public { address _customerAddress = msg.sender; NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; require(_newActiveIndex < customerNamesInfo.registeredNames.length); customerNamesInfo.activeIndex = _newActiveIndex; } /** * Converts all of caller's dividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvest(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 reinvestableDividends = dividendsStored_[_customerAddress]; reinvestAmount(reinvestableDividends); } /** * Converts a portion of caller's dividends to tokens. */ function reinvestAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _amountOfP3D, address(0x0)); // fire event emit onReinvestment(_customerAddress, _amountOfP3D, _tokens); } } /** * Converts all of caller's subdividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvestSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 reinvestableSubdividends = divsMap_[_customerAddress].balance; reinvestSubdivsAmount(reinvestableSubdividends); } /** * Converts a portion of caller's subdividends to tokens. */ function reinvestSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // purchase tokens with the ETH subdividends uint256 _tokens = purchaseInternal(_customerAddress, _amountOfETH, address(0x0)); // fire event emit onSubdivsReinvestment(_customerAddress, _amountOfETH, _tokens); } } /** * Alias of sell(), withdraw() and withdrawSubdivs(). * The argument is not used but it allows MetaMask to render * 'Exit' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function exit(bool) public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(true); withdrawSubdivs(true); } /** * Withdraws all of the callers dividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdraw(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 withdrawableDividends = dividendsStored_[_customerAddress]; withdrawAmount(withdrawableDividends); } /** * Withdraws a portion of the callers dividend earnings. */ function withdrawAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // lambo delivery service require(_P3D.transfer(_customerAddress, _amountOfP3D)); // NOTE! // P3D has a 10% transfer tax so even though this is sending your entire // dividend count to you, you will only actually receive 90%. // fire event emit onWithdraw(_customerAddress, _amountOfP3D); } } /** * Withdraws all of the callers subdividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdrawSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 withdrawableSubdividends = divsMap_[_customerAddress].balance; withdrawSubdivsAmount(withdrawableSubdividends); } /** * Withdraws a portion of the callers subdividend earnings. */ function withdrawSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // transfer all withdrawable subdividends _customerAddress.transfer(_amountOfETH); // fire event emit onSubdivsWithdraw(_customerAddress, _amountOfETH); } } /** * Liquifies tokens to P3D. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _P3D_amount = tokensToP3D_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_amount, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_amount, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256)(profitPerShare_ * _tokens + (_taxedP3D * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire events emit onTokenSell(_customerAddress, _tokens, _taxedP3D); emit Transfer(_customerAddress, address(0x0), _tokens); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; return transferInternal(_customerAddress, _toAddress, _amountOfTokens); } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(canAcceptTokens_[_to]); // approved contracts only require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { usingP4D receiver = usingP4D(_to); require(receiver.tokenCallback(msg.sender, _value, _data)); } return true; } /** * ERC-20 token standard for transferring tokens on anothers behalf */ function transferFrom(address _from, address _to, uint256 _amountOfTokens) public returns(bool) { require(allowed[_from][msg.sender] >= _amountOfTokens); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); return transferInternal(_from, _to, _amountOfTokens); } /** * ERC-20 token standard for allowing another address to transfer your tokens * on your behalf up to a certain limit */ function approve(address _spender, uint256 _tokens) public returns(bool) { allowed[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /** * ERC-20 token standard for approving and calling an external * contract with data */ function approveAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(approve(_to, _value)); // do a normal approval if (isContract(_to)) { controllingP4D receiver = controllingP4D(_to); require(receiver.approvalCallback(msg.sender, _value, _data)); } return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Add a new ambassador to the exchange */ function setAmbassador(address _identifier, bool _status) onlyAdministrator() public { ambassadors_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add a sub-contract, which can accept P4D tokens */ function setCanAcceptTokens(address _address) onlyAdministrator() public { require(isContract(_address)); canAcceptTokens_[_address] = true; // one way switch } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current P3D tokens stored in the contract */ function totalBalance() public view returns(uint256) { return _P3D.myTokens(); } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is set to true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return (_includeReferralBonus ? dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress) : dividendsOf(_customerAddress)); } /** * Retrieve the subdividend owned by the caller. */ function myStoredDividends() public view returns(uint256) { address _customerAddress = msg.sender; return storedDividendsOf(_customerAddress); } /** * Retrieve the subdividend owned by the caller. */ function mySubdividends() public view returns(uint256) { address _customerAddress = msg.sender; return subdividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) public view returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) public view returns(uint256) { return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Retrieve the referred dividend balance of any single address. */ function referralDividendsOf(address _customerAddress) public view returns(uint256) { return referralBalance_[_customerAddress]; } /** * Retrieve the stored dividend balance of any single address. */ function storedDividendsOf(address _customerAddress) public view returns(uint256) { return dividendsStored_[_customerAddress] + dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); } /** * Retrieve the subdividend balance owing of any single address. */ function subdividendsOwing(address _customerAddress) public view returns(uint256) { return (divsMap_[_customerAddress].lastDividendPoints == 0 ? 0 : (balanceOf(_customerAddress) * (totalDividendPoints_ - divsMap_[_customerAddress].lastDividendPoints)) / magnitude); } /** * Retrieve the subdividend balance of any single address. */ function subdividendsOf(address _customerAddress) public view returns(uint256) { return SafeMath.add(divsMap_[_customerAddress].balance, subdividendsOwing(_customerAddress)); } /** * Retrieve the allowance of an owner and spender. */ function allowance(address _tokenOwner, address _spender) public view returns(uint256) { return allowed[_tokenOwner][_spender]; } /** * Retrieve all name information about a customer */ function namesOf(address _customerAddress) public view returns(uint256 activeIndex, string activeName, bytes32[] customerNames) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; uint256 length = customerNamesInfo.registeredNames.length; customerNames = new bytes32[](length); for (uint256 i = 0; i < length; i++) { customerNames[i] = customerNamesInfo.registeredNames[i]; } activeIndex = customerNamesInfo.activeIndex; activeName = activeNameOf(_customerAddress); } /** * Retrieves the address of the owner from the name */ function ownerOfName(string memory _name) public view returns(address) { if (bytes(_name).length > 0) { bytes32 bytesName = stringToBytes32(_name); return globalNameMap_[bytesName]; } else { return address(0x0); } } /** * Retrieves the active name of a customer */ function activeNameOf(address _customerAddress) public view returns(string) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; if (customerNamesInfo.registeredNames.length > 0) { bytes32 activeBytesName = customerNamesInfo.registeredNames[customerNamesInfo.activeIndex]; return bytes32ToString(activeBytesName); } else { return ""; } } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.add(_P3D_received, _dividends); return _taxedP3D; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _amountOfETH) public view returns(uint256 _P3D_received, uint256 _P4D_received) { uint256 P3D_received = _P3D.calculateTokensReceived(_amountOfETH); uint256 _dividends = SafeMath.div(SafeMath.mul(P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(P3D_received, _dividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); return (P3D_received, _amountOfTokens); } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateAmountReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _P3D_received = tokensToP3D_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } /** * Utility method to expose the P3D address for any child contracts to use */ function P3D_address() public view returns(address) { return address(_P3D); } /** * Utility method to return all of the data needed for the front end in 1 call */ function fetchAllDataForCustomer(address _customerAddress) public view returns(uint256 _totalSupply, uint256 _totalBalance, uint256 _buyPrice, uint256 _sellPrice, uint256 _activationTime, uint256 _customerTokens, uint256 _customerUnclaimedDividends, uint256 _customerStoredDividends, uint256 _customerSubdividends) { _totalSupply = totalSupply(); _totalBalance = totalBalance(); _buyPrice = buyPrice(); _sellPrice = sellPrice(); _activationTime = ACTIVATION_TIME; _customerTokens = balanceOf(_customerAddress); _customerUnclaimedDividends = dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); _customerStoredDividends = storedDividendsOf(_customerAddress); _customerSubdividends = subdividendsOf(_customerAddress); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // This function should always be called before a customers P4D balance changes. // It's responsible for withdrawing any outstanding ETH dividends from the P3D exchange // as well as distrubuting all of the additional ETH balance since the last update to // all of the P4D token holders proportionally. // After this it will move any owed subdividends into the customers withdrawable subdividend balance. function updateSubdivsFor(address _customerAddress) internal { // withdraw the P3D dividends first if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } // check if we have additional ETH in the contract since the last update uint256 contractBalance = address(this).balance; if (contractBalance > lastContractBalance_ && totalSupply() != 0) { uint256 additionalDivsFromP3D = SafeMath.sub(contractBalance, lastContractBalance_); totalDividendPoints_ = SafeMath.add(totalDividendPoints_, SafeMath.div(SafeMath.mul(additionalDivsFromP3D, magnitude), totalSupply())); lastContractBalance_ = contractBalance; } // if this is the very first time this is called for a customer, set their starting point if (divsMap_[_customerAddress].lastDividendPoints == 0) { divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } // move any owing subdividends into the customers subdividend balance uint256 owing = subdividendsOwing(_customerAddress); if (owing > 0) { divsMap_[_customerAddress].balance = SafeMath.add(divsMap_[_customerAddress].balance, owing); divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } } function withdrawInternal(address _customerAddress) internal { // setup data // dividendsOf() will return only divs, not the ref. bonus uint256 _dividends = dividendsOf(_customerAddress); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // store the divs dividendsStored_[_customerAddress] = SafeMath.add(dividendsStored_[_customerAddress], _dividends); } function transferInternal(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns(bool) { // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress); // withdraw and store all outstanding dividends first (if there is any) if ((dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress)) > 0) withdrawInternal(_customerAddress); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256)(profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function purchaseInternal(address _sender, uint256 _incomingEthereum, address _referredBy) purchaseFilter(_sender, _incomingEthereum) internal returns(uint256) { uint256 purchaseAmount = _incomingEthereum; uint256 excess = 0; if (totalInputETH_ <= initialBuyLimitCap_) { // check if the total input ETH is less than the cap if (purchaseAmount > initialBuyLimitPerTx_) { // if so check if the transaction is over the initial buy limit per transaction purchaseAmount = initialBuyLimitPerTx_; excess = SafeMath.sub(_incomingEthereum, purchaseAmount); } totalInputETH_ = SafeMath.add(totalInputETH_, purchaseAmount); } // return the excess if there is any if (excess > 0) { _sender.transfer(excess); } // buy P3D tokens with the entire purchase amount // even though _P3D.buy() returns uint256, it was never implemented properly inside the P3D contract // so in order to find out how much P3D was purchased, you need to check the balance first then compare // the balance after the purchase and the difference will be the amount purchased uint256 tmpBalanceBefore = _P3D.myTokens(); _P3D.buy.value(purchaseAmount)(_referredBy); uint256 purchasedP3D = SafeMath.sub(_P3D.myTokens(), tmpBalanceBefore); return purchaseTokens(_sender, purchasedP3D, _referredBy); } function purchaseTokens(address _sender, uint256 _incomingP3D, address _referredBy) internal returns(uint256) { updateSubdivsFor(_sender); // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingP3D, buyDividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedP3D = SafeMath.sub(_incomingP3D, _undividedDividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != address(0x0) && // no cheating! _referredBy != _sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite P3D if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over their purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_sender] = SafeMath.add(tokenBalanceLedger_[_sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really I know you think you do but you don't payoutsTo_[_sender] += (int256)((profitPerShare_ * _amountOfTokens) - _fee); // fire events emit onTokenPurchase(_sender, _incomingP3D, _amountOfTokens, _referredBy); emit Transfer(address(0x0), _sender, _amountOfTokens); return _amountOfTokens; } /** * Calculate token price based on an amount of incoming P3D * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function P3DtoTokens_(uint256 _P3D_received) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2 * (tokenPriceIncremental_ * 1e18)*(_P3D_received * 1e18)) + (((tokenPriceIncremental_)**2) * (tokenSupply_**2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToP3D_(uint256 _P4D_tokens) internal view returns(uint256) { uint256 tokens_ = (_P4D_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _P3D_received = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2 ) / 1e18); return _P3D_received; } // This is where all your gas goes, sorry // Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /** * Additional check that the address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) internal constant returns(bool) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /** * Utility method to help store the registered names */ function stringToBytes32(string memory _s) internal pure returns(bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility method to help read the registered names */ function bytes32ToString(bytes32 _b) internal pure returns(string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // // pragma solidity ^0.4.25; // // interface P4D { // function buy(address) external payable returns(uint256); // function sell(uint256) external; // function transfer(address, uint256) external returns(bool); // function myTokens() external view returns(uint256); // function myStoredDividends() external view returns(uint256); // function mySubdividends() external view returns(uint256); // function reinvest(bool) external; // function reinvestSubdivs(bool) external; // function withdraw(bool) external; // function withdrawSubdivs(bool) external; // function exit(bool) external; // sell + withdraw + withdrawSubdivs // function P3D_address() external view returns(address); // } // // contract usingP4D { // // P4D public tokenContract; // // constructor(address _P4D_address) public { // tokenContract = P4D(_P4D_address); // } // // modifier onlyTokenContract { // require(msg.sender == address(tokenContract)); // _; // } // // function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); // } // // contract YourDapp is usingP4D { // // constructor(address _P4D_address) // public // usingP4D(_P4D_address) // { // //... // } // // function tokenCallback(address _from, uint256 _value, bytes _data) // external // onlyTokenContract // returns (bool) // { // //... // return true; // } // // function() // payable // public // { // if (msg.sender != address(tokenContract)) { // //... // } // } // } // /*===========================================================================================* *************************************** https://p4d.io *************************************** *===========================================================================================*/
* Retrieve the token balance of any single address./
function balanceOf(address _customerAddress) public view returns(uint256) { return tokenBalanceLedger_[_customerAddress]; }
7,264,064
[ 1, 5767, 326, 1147, 11013, 434, 1281, 2202, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 389, 10061, 1887, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x90F11d777B76ce0C6066a06fa5eF7BF9ea4770a6/sources/tokenSale.sol
busd.transferFrom(msg.sender, address(this), amount);
uint256 ethToUsd = calculateUsd(amount);
2,838,769
[ 1, 9274, 72, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 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 ]
[ 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, 3639, 2254, 5034, 13750, 774, 3477, 72, 273, 225, 4604, 3477, 72, 12, 8949, 1769, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x83487B13e7B68536047B10A79b37FBe74eE8B394/sources/contracts/DirectTokenV2.sol
* @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 payable onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
17,146,885
[ 1, 1682, 6606, 326, 6835, 2887, 3410, 18, 2597, 903, 486, 506, 3323, 358, 745, 1375, 3700, 5541, 68, 4186, 16828, 18, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 5219, 30, 25921, 465, 2822, 23178, 903, 8851, 326, 6835, 2887, 392, 3410, 16, 1915, 1637, 9427, 1281, 14176, 716, 353, 1338, 2319, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 8843, 429, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 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 ]
./full_match/80001/0x42477702a7A96e97A0Dbcc1081a29c08e600E457/sources/contracts/W3BadgeContract.sol
* @dev Give the counter of points for the current user / player/
function myCurrentPoints() public view returns(uint256){ return points[msg.sender]; }
872,415
[ 1, 43, 688, 326, 3895, 434, 3143, 364, 326, 783, 729, 342, 7291, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3399, 3935, 5636, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 3143, 63, 3576, 18, 15330, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY419() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF996(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER376(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE696(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE263(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM581(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER351(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL946(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB882(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB882(a, b, "SafeMath: subtraction overflow"); } function SUB882(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 MUL339(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 DIV809(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV809(a, b, "SafeMath: division by zero"); } function DIV809(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 MOD891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD891(a, b, "SafeMath: modulo by zero"); } function MOD891(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT313(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 TOPAYABLE45(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE473(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER885(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFER376.selector, to, value)); } function SAFETRANSFERFROM553(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.TRANSFERFROM581.selector, from, to, value)); } function SAFEAPPROVE341(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.ALLOWANCE696(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, value)); } function SAFEINCREASEALLOWANCE60(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE696(address(this), spender).ADD509(value); CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE623(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE696(address(this), spender).SUB882(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN246(token, abi.encodeWithSelector(token.APPROVE263.selector, spender, newAllowance)); } function CALLOPTIONALRETURN246(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).ISCONTRACT313(), "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 IController { function WITHDRAW936(address, uint256) external; //inject NONSTANDARD NAMING function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING function EARN112(address, uint256) external; //inject NONSTANDARD NAMING function WANT318(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS351() external view returns (address); //inject NONSTANDARD NAMING function VAULTS378(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES650(address) external view returns (address); //inject NONSTANDARD NAMING } // interface Gauge { function DEPOSIT828(uint256) external; //inject NONSTANDARD NAMING function BALANCEOF996(address) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW936(uint256) external; //inject NONSTANDARD NAMING } // interface Mintr { function MINT422(address) external; //inject NONSTANDARD NAMING } // interface Uni { function SWAPEXACTTOKENSFORTOKENS240( //inject NONSTANDARD NAMING uint256, uint256, address[] calldata, address, uint256 ) external; } // interface ICurveFi { function GET_VIRTUAL_PRICE800() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function ADD_LIQUIDITY808( //inject NONSTANDARD NAMING // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY_IMBALANCE228(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING function REMOVE_LIQUIDITY138(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING function EXCHANGE730( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } interface Zap { function REMOVE_LIQUIDITY_ONE_COIN571( //inject NONSTANDARD NAMING uint256, int128, uint256 ) external; } // // NOTE: Basically an alias for Vaults interface yERC20 { function DEPOSIT828(uint256 _amount) external; //inject NONSTANDARD NAMING function WITHDRAW936(uint256 _amount) external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE410() external view returns (uint256); //inject NONSTANDARD NAMING } // interface VoterProxy { function WITHDRAW936( //inject NONSTANDARD NAMING address _gauge, address _token, uint256 _amount ) external returns (uint256); function BALANCEOF996(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAWALL4(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT828(address _gauge, address _token) external; //inject NONSTANDARD NAMING function HARVEST862(address _gauge) external; //inject NONSTANDARD NAMING function LOCK494() external; //inject NONSTANDARD NAMING } // contract StrategyCurveBUSDVoterProxy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want963 = address(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); //inject NONSTANDARD NAMING address public constant crv787 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING address public constant uni793 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant weth737 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address public constant dai668 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public constant ydai985 = address(0xa3Aa4a71dBb17EBF2108A75b0BB7eFd9955463EF);//itoken //inject NONSTANDARD NAMING address public constant curve489 = address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); //inject NONSTANDARD NAMING address public constant gauge170 = address(0x69Fb7c45726cfE2baDeE8317005d3F94bE838840); //inject NONSTANDARD NAMING address public constant voter494 = address(0x07443C1cdb3653746727D595D2c1e5B438e0535A);//CurveYCRVVoter //inject NONSTANDARD NAMING uint256 public keepCRV = 1000; uint256 public constant keepcrvmax536 = 10000; //inject NONSTANDARD NAMING uint256 public performanceFee = 3000; uint256 public constant performancemax55 = 10000; //inject NONSTANDARD NAMING uint256 public withdrawalFee = 50; uint256 public constant withdrawalmax744 = 10000; //inject NONSTANDARD NAMING address public proxy; address public governance; address public controller; address public strategist; constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function GETNAME315() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyCurveBUSDVoterProxy"; } function SETSTRATEGIST730(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETKEEPCRV658(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } function SETWITHDRAWALFEE696(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE960(uint256 _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETPROXY105(address _proxy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); proxy = _proxy; } function DEPOSIT828() public { //inject NONSTANDARD NAMING uint256 _want = IERC20(want963).BALANCEOF996(address(this)); if (_want > 0) { IERC20(want963).SAFETRANSFER885(proxy, _want); VoterProxy(proxy).DEPOSIT828(gauge170, want963); } } // Controller only function for creating additional rewards from dust function WITHDRAW936(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want963 != address(_asset), "want"); require(crv787 != address(_asset), "crv"); require(ydai985 != address(_asset), "ydai"); require(dai668 != address(_asset), "dai"); balance = _asset.BALANCEOF996(address(this)); _asset.SAFETRANSFER885(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW936(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want963).BALANCEOF996(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME256(_amount.SUB882(_balance)); _amount = _amount.ADD509(_balance); } uint256 _fee = _amount.MUL339(withdrawalFee).DIV809(withdrawalmax744); IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee); address _vault = IController(controller).VAULTS378(address(want963)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want963).SAFETRANSFER885(_vault, _amount.SUB882(_fee)); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL4() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL830(); balance = IERC20(want963).BALANCEOF996(address(this)); address _vault = IController(controller).VAULTS378(address(want963)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want963).SAFETRANSFER885(_vault, balance); } function _WITHDRAWALL830() internal { //inject NONSTANDARD NAMING VoterProxy(proxy).WITHDRAWALL4(gauge170, want963); } function HARVEST862() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!authorized"); VoterProxy(proxy).HARVEST862(gauge170); uint256 _crv = IERC20(crv787).BALANCEOF996(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.MUL339(keepCRV).DIV809(keepcrvmax536); IERC20(crv787).SAFETRANSFER885(voter494, _keepCRV); _crv = _crv.SUB882(_keepCRV); IERC20(crv787).SAFEAPPROVE341(uni793, 0); IERC20(crv787).SAFEAPPROVE341(uni793, _crv); address[] memory path = new address[](3); path[0] = crv787; path[1] = weth737; path[2] = dai668; Uni(uni793).SWAPEXACTTOKENSFORTOKENS240(_crv, uint256(0), path, address(this), now.ADD509(1800)); } uint256 _dai = IERC20(dai668).BALANCEOF996(address(this)); if (_dai > 0) { IERC20(dai668).SAFEAPPROVE341(ydai985, 0); IERC20(dai668).SAFEAPPROVE341(ydai985, _dai); yERC20(ydai985).DEPOSIT828(_dai); } uint256 _ydai = IERC20(ydai985).BALANCEOF996(address(this)); if (_ydai > 0) { IERC20(ydai985).SAFEAPPROVE341(curve489, 0); IERC20(ydai985).SAFEAPPROVE341(curve489, _ydai); ICurveFi(curve489).ADD_LIQUIDITY808([_ydai, 0, 0, 0], 0); } uint256 _want = IERC20(want963).BALANCEOF996(address(this)); if (_want > 0) { uint256 _fee = _want.MUL339(performanceFee).DIV809(performancemax55); IERC20(want963).SAFETRANSFER885(IController(controller).REWARDS351(), _fee); DEPOSIT828(); } VoterProxy(proxy).LOCK494(); } function _WITHDRAWSOME256(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).WITHDRAW936(gauge170, want963, _amount); } function BALANCEOFWANT761() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(want963).BALANCEOF996(address(this)); } function BALANCEOFPOOL660() public view returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).BALANCEOF996(gauge170); } function BALANCEOF996() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFWANT761().ADD509(BALANCEOFPOOL660()); } function SETGOVERNANCE812(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER990(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
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).ISCONTRACT313(), "SafeERC20: call to non-contract");
12,870,923
[ 1, 37, 348, 7953, 560, 3551, 1801, 745, 711, 8925, 2140, 30, 225, 404, 18, 1021, 1018, 1758, 353, 5950, 358, 3929, 518, 1914, 6835, 981, 225, 576, 18, 1021, 745, 6174, 353, 7165, 16, 471, 2216, 1815, 329, 225, 890, 18, 1021, 327, 460, 353, 6383, 16, 1492, 316, 7005, 4271, 326, 963, 434, 326, 2106, 501, 18, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 943, 17, 1369, 17, 2469, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 2867, 12, 2316, 2934, 5127, 6067, 2849, 1268, 23, 3437, 9334, 315, 9890, 654, 39, 3462, 30, 745, 358, 1661, 17, 16351, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20() public { totalSupply = 100000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "expime"; // Set the name for display purposes symbol = "EXM"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
Set the symbol for display purposes
symbol = "EXM";
9,917,598
[ 1, 694, 326, 3273, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3273, 273, 315, 2294, 49, 14432, 27573, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x3fF05109BE3D5D56d582A385e3E587AD39cC16Dd/sources/project_/contracts/Peepee.sol
Return an empty array
function getOwnedPeepees(address _holder) external view returns(uint[] memory) { uint tokenCount = pepe2d.balanceOf(_holder); if (tokenCount == 0) { return new uint[](0); uint[] memory result = new uint[](tokenCount); uint index; for(uint i=1;i<=TOTAL_PEEPEE_2DS;i++) { if(pepe2d.ownerOf(i) == _holder){ result[index] = i; index += 1; } } return result; } }
1,883,157
[ 1, 990, 392, 1008, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 5460, 329, 52, 1340, 347, 281, 12, 2867, 389, 4505, 13, 3903, 1476, 1135, 12, 11890, 8526, 3778, 13, 288, 203, 3639, 2254, 1147, 1380, 273, 2804, 347, 22, 72, 18, 12296, 951, 24899, 4505, 1769, 203, 3639, 309, 261, 2316, 1380, 422, 374, 13, 288, 203, 5411, 327, 394, 2254, 8526, 12, 20, 1769, 203, 5411, 2254, 8526, 3778, 563, 273, 394, 2254, 8526, 12, 2316, 1380, 1769, 203, 5411, 2254, 770, 31, 203, 5411, 364, 12, 11890, 277, 33, 21, 31, 77, 32, 33, 28624, 67, 1423, 41, 1423, 41, 67, 22, 3948, 31, 77, 27245, 288, 203, 7734, 309, 12, 347, 347, 22, 72, 18, 8443, 951, 12, 77, 13, 422, 389, 4505, 15329, 203, 10792, 563, 63, 1615, 65, 273, 277, 31, 203, 10792, 770, 1011, 404, 31, 203, 7734, 289, 203, 5411, 289, 203, 5411, 327, 563, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/Counters.sol"; interface ICifEsportsMultiTrophy { function trophies(uint256 trophyId) external view returns ( string calldata tournament, bytes32 infoHash, uint256 timeReceived, uint256[] calldata winnerIds ); function transferOwnership(address newOwner) external; function hasAddressCurrentTrophy(address holder) external view returns (bool); function currentTrophyId() external view returns (uint256 trophyId); function setBaseURI(string memory baseURI) external; function passTrophy( string memory _tournament, bytes32 _infoHash, address[] memory _winnerAddresses, string[] memory _winnerNames ) external; } /// @title Governance Contract for the CIF Esports Trophy /// @author Matthias Nadler, University of Basel /// @notice Implements flexible quorum voting for governance members contract CifGovernance { using Counters for Counters.Counter; event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event MemberAddition(address indexed member); event MemberRemoval(address indexed member); event QuorumChange(uint256 indexed oldQuorum, uint256 indexed newQuorum); address immutable public cifTrophyAddress; ICifEsportsMultiTrophy private _cifTrophy; mapping(address => bool) public isMember; address[] public members; uint256 public quorum; // In percent of members (0-100) uint256 public requiredVotes; // Transactions and Payloads (Information Containers) // -------------------------------------------------- // Payloads are mappings that use the same ID as the underlying transaction. // Each Transaction uses exactly one payload, depending on its type. enum TransactionType { invalid, addMember, removeMember, replaceMember, passTrophy, transferOwnership, changeQuorum, setBaseURI } struct Transaction { TransactionType txnType; bool executed; } Counters.Counter public transactionCount; mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(address => bool)) public confirmations; mapping(uint256 => address) public addressPayloads; mapping(uint256 => uint256) public uintPayloads; mapping(uint256 => string) public stringPayloads; struct ReplaceMemberPayload { address oldMember; address newMember; } mapping(uint256 => ReplaceMemberPayload) public replaceMemberPayloads; struct PassTrophyPayload { uint256 currentTrophyId; string tournament; bytes32 infoHash; address[] winnerAddresses; string[] winnerNames; } mapping(uint256 => PassTrophyPayload) public passTrophyPayloads; // Modifiers modifier onlyMember() { require(isMember[msg.sender], "Gov: caller is not a member"); _; } modifier validTransaction(uint256 _transactionId) { require(uint256(transactions[_transactionId].txnType) > 0, "Gov: invalid transaction"); _; } // Contract Functions constructor (address _cifTrophyAddress, uint256 _initialQuorum, address[] memory _members) public { quorum = _initialQuorum; uint256 nMembers = _members.length; for (uint256 i = 0; i < nMembers; i++) { isMember[_members[i]] = true; } members = _members; _updateRequiredVotes(); // The reference to the CIF Trophy contract can never be changed cifTrophyAddress = _cifTrophyAddress; _cifTrophy = ICifEsportsMultiTrophy(_cifTrophyAddress); } /// @dev Always rounds up to the next full number of members function _updateRequiredVotes() internal { requiredVotes = (members.length * quorum + 99) / 100; } function addMember(address _newMember) public onlyMember returns (uint256 transactionId) { require(_newMember != address(0), "Gov: new member is the zero address"); require(!isMember[_newMember], "Gov: member already exists"); transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.addMember, false); addressPayloads[transactionId] = _newMember; emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } function _addMember(uint256 _transactionId) internal validTransaction(_transactionId) { address _newMember = addressPayloads[_transactionId]; require(_newMember != address(0), "Gov: new member is the zero address"); require(!isMember[_newMember], "Gov: member already exists"); isMember[_newMember] = true; members.push(_newMember); _updateRequiredVotes(); emit MemberAddition(_newMember); } function removeMember(address _oldMember) public onlyMember returns (uint256 transactionId){ require(isMember[_oldMember], "Gov: member does not exist"); transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.removeMember, false); addressPayloads[transactionId] = _oldMember; emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } function _removeMember(uint256 _transactionId) internal validTransaction(_transactionId) { address _oldMember = addressPayloads[_transactionId]; require(isMember[_oldMember], "Gov: member does not exist"); isMember[_oldMember] = false; for (uint256 i = 0; i < members.length - 1; i++) { if (members[i] == _oldMember) { members[i] = members[members.length - 1]; break; } } members.pop(); _updateRequiredVotes(); emit MemberRemoval(_oldMember); } function replaceMember(address _oldMember, address _newMember) public onlyMember returns (uint256 transactionId){ require(_newMember != address(0), "Gov: new member is the zero address"); require(isMember[_oldMember], "Gov: old member does not exist"); require(!isMember[_newMember], "Gov: new member already exists"); transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.replaceMember, false); replaceMemberPayloads[transactionId] = ReplaceMemberPayload(_oldMember, _newMember); emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } /// @dev More efficient than remove -> add function _replaceMember(uint256 _transactionId) internal validTransaction(_transactionId) { ReplaceMemberPayload storage _replacementAddresses = replaceMemberPayloads[_transactionId]; require(_replacementAddresses.newMember != address(0), "Gov: new member is the zero address"); require(isMember[_replacementAddresses.oldMember], "Gov: old member does not exist"); require(!isMember[_replacementAddresses.newMember], "Gov: new member already exists"); isMember[_replacementAddresses.oldMember] = false; isMember[_replacementAddresses.newMember] = true; for (uint256 i = 0; i < members.length; i++) { if (members[i] == _replacementAddresses.oldMember) { members[i] = _replacementAddresses.newMember; break; } } emit MemberRemoval(_replacementAddresses.oldMember); emit MemberAddition(_replacementAddresses.newMember); } function passTrophy( string memory _tournament, bytes32 _infoHash, address[] memory _winnerAddresses, string[] memory _winnerNames ) public onlyMember returns (uint256 transactionId) { require(_winnerAddresses.length == _winnerNames.length, "Gov: not same length for address- and name arrays"); uint256 currentTrophyId = _cifTrophy.currentTrophyId(); // Conditions for passing the trophy without quorum: // This prevents winners from passing the trophy to themselves. // 1. The transaction sender must be a governance member (checked in modifier) // 2. The transaction sender must own a token of the current trophy // 3. The transaction sender can't be a winner of the next trophy // 4. All winners of the next trophy must be governance members if (_cifTrophy.hasAddressCurrentTrophy(msg.sender)) { bool conditionsOk = true; for (uint256 i=0; i<_winnerAddresses.length; i++) { if (_winnerAddresses[i] == msg.sender || !isMember[_winnerAddresses[i]]) { conditionsOk = false; break; } } if (conditionsOk) { // No transaction is created, trophy is passed immediately _cifTrophy.passTrophy(_tournament, _infoHash, _winnerAddresses, _winnerNames); return 0; } } // Otherwise start a quorum vote to pass the trophy transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.passTrophy, false); passTrophyPayloads[transactionId] = PassTrophyPayload( currentTrophyId, _tournament, _infoHash, _winnerAddresses, _winnerNames ); emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } function _passTrophy(uint256 _transactionId) internal validTransaction(_transactionId) { PassTrophyPayload storage payload = passTrophyPayloads[_transactionId]; require(payload.currentTrophyId == _cifTrophy.currentTrophyId(), "Gov: trophy has been passed already"); _cifTrophy.passTrophy( payload.tournament, payload.infoHash, payload.winnerAddresses, payload.winnerNames ); } function transferOwnership(address _newOwner) public onlyMember returns (uint256 transactionId){ require(_newOwner != address(0), "Gov: new owner is the zero address"); transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.transferOwnership, false); addressPayloads[transactionId] = _newOwner; emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } function _transferOwnership(uint256 _transactionId) internal validTransaction(_transactionId) { _cifTrophy.transferOwnership(addressPayloads[_transactionId]); } function changeQuorum(uint256 _newQuorum) public onlyMember returns (uint256 transactionId){ require(_newQuorum <= 100, "Gov: new quorum must be between 0 and 100"); transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.changeQuorum, false); uintPayloads[transactionId] = _newQuorum; emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } function _changeQuorum(uint256 _transactionId) internal validTransaction(_transactionId) { uint256 _newQuorum = uintPayloads[_transactionId]; uint256 _oldQuorum = quorum; quorum = _newQuorum; _updateRequiredVotes(); emit QuorumChange(_oldQuorum, _newQuorum); } function setBaseURI(string memory _baseURI) public onlyMember returns (uint256 transactionId){ transactionCount.increment(); transactionId = transactionCount.current(); transactions[transactionId] = Transaction(TransactionType.setBaseURI, false); stringPayloads[transactionId] = _baseURI; emit Submission(transactionId); confirmTransaction(transactionId); return transactionId; } function _setBaseURI(uint256 _transactionId) internal validTransaction(_transactionId) { _cifTrophy.setBaseURI(stringPayloads[_transactionId]); } function confirmTransaction(uint256 _transactionId) public onlyMember validTransaction(_transactionId) { require(!transactions[_transactionId].executed, "Gov: transaction already executed"); require(!confirmations[_transactionId][msg.sender], "Gov: transaction already confirmed"); confirmations[_transactionId][msg.sender] = true; emit Confirmation(msg.sender, _transactionId); executeTransaction(_transactionId); } function revokeConfirmation(uint256 _transactionId) public onlyMember validTransaction(_transactionId) { require(!transactions[_transactionId].executed, "Gov: transaction already executed"); require(confirmations[_transactionId][msg.sender], "Gov: transaction not confirmed"); confirmations[_transactionId][msg.sender] = false; emit Revocation(msg.sender, _transactionId); } function executeTransaction(uint256 _transactionId) public onlyMember validTransaction(_transactionId) returns (bool success){ require(!transactions[_transactionId].executed, "Gov: transaction already executed"); if (isConfirmed(_transactionId)) { Transaction storage txn = transactions[_transactionId]; txn.executed = true; if (txn.txnType == TransactionType.addMember) { _addMember(_transactionId); } else if (txn.txnType == TransactionType.removeMember) { _removeMember(_transactionId); } else if (txn.txnType == TransactionType.replaceMember) { _replaceMember(_transactionId); } else if(txn.txnType == TransactionType.transferOwnership) { _transferOwnership(_transactionId); } else if (txn.txnType == TransactionType.passTrophy) { _passTrophy(_transactionId); } else if (txn.txnType == TransactionType.changeQuorum) { _changeQuorum(_transactionId); } else if (txn.txnType == TransactionType.setBaseURI) { _setBaseURI(_transactionId); } else { emit ExecutionFailure(_transactionId); return false; } emit Execution(_transactionId); return true; } return false; } function isConfirmed(uint256 _transactionId) public view validTransaction(_transactionId) returns (bool) { uint256 count = 0; for (uint256 i = 0; i < members.length; i++) { if (confirmations[_transactionId][members[i]]) { count += 1; } if (count == requiredVotes) { return true; } } return false; } // Web3 View Functions function getConfirmationCount(uint256 _transactionId) public view validTransaction(_transactionId) returns (uint256 count) { for (uint256 i=0; i<members.length; i++) { if (confirmations[_transactionId][members[i]]) { count += 1; } } return count; } function getMembers() external view returns (address[] memory _members) { return members; } function getConfirmations(uint256 _transactionId) external view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](members.length); uint256 count = 0; uint256 i; for (i=0; i<members.length; i++) { if (confirmations[_transactionId][members[i]]) { confirmationsTemp[count] = members[i]; count += 1; } } _confirmations = new address[](count); for (i=0; i<count; i++) { _confirmations[i] = confirmationsTemp[i]; } } function getTransactionIds(bool isExecuted) external view returns (uint256[] memory _transactionIds) { uint256[] memory transactionIdsTemp = new uint[](transactionCount.current()); uint256 count = 0; uint256 i; for (i=1; i<=transactionCount.current(); i++) { if (transactions[i].executed == isExecuted) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint256[](count); for (i=0; i<count; i++) { _transactionIds[i] = transactionIdsTemp[i]; } return _transactionIds; } }
Otherwise start a quorum vote to pass the trophy
transactionCount.increment();
13,111,771
[ 1, 8290, 2460, 787, 279, 31854, 12501, 358, 1342, 326, 23432, 844, 93, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 2492, 1380, 18, 15016, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x765C7CFED02f2d9583EAc8229930f3650AF42C77/sources/contracts/REDACTEDBondDepositoryRewardBased.sol
* @notice debt ratio in same terms for reserve or liquidity bonds @return uint/
function standardizedDebtRatio() external view returns (uint256) { if (isLiquidityBond) { return debtRatio().mul(IBondCalculator(bondCalculator).markdown(principal)).div(1e9); return debtRatio(); } }
2,990,034
[ 1, 323, 23602, 7169, 316, 1967, 6548, 364, 20501, 578, 4501, 372, 24237, 15692, 225, 327, 2254, 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, 225, 445, 4529, 1235, 758, 23602, 8541, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 291, 48, 18988, 24237, 9807, 13, 288, 203, 1377, 327, 18202, 88, 8541, 7675, 16411, 12, 45, 9807, 19278, 12, 26425, 19278, 2934, 20090, 12, 26138, 13, 2934, 2892, 12, 21, 73, 29, 1769, 203, 1377, 327, 18202, 88, 8541, 5621, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//! Copyright 2017 Peter Czaban, Parity Technologies Ltd. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. pragma solidity ^0.4.15; import "./interfaces/RelaySet.sol"; import "./libraries/AddressVotes.sol"; // Existing validators can give support to addresses. // Support can not be added once MAX_VALIDATORS are present. // Once given, support can be removed. // Addresses supported by more than half of the existing validators are the validators. // Malicious behaviour causes support removal. // Benign misbehaviour causes supprt removal if its called again after MAX_INACTIVITY. // Benign misbehaviour can be absolved before being called the second time. contract InnerMajoritySet is InnerSet { // EVENTS event Report(address indexed reporter, address indexed reported, bool indexed malicious); event Support(address indexed supporter, address indexed supported, bool indexed added); event InitiateChange(bytes32 indexed _parent_hash, address[] _new_set); event ChangeFinalized(address[] current_set); struct ValidatorStatus { // Is this a validator. bool isValidator; // Index in the validatorList. uint index; // Validator addresses which supported the address. AddressVotes.Data support; // Keeps track of the votes given out while the address is a validator. address[] supported; // Initial benign misbehaviour time tracker. mapping(address => uint) firstBenign; // Repeated benign misbehaviour counter. AddressVotes.Data benignMisbehaviour; } // Support can not be added once this number of validators is reached. uint public constant MAX_VALIDATORS = 30; // Time after which the validators will report a validator as malicious. uint public constant MAX_INACTIVITY = 6 hours; // Ignore misbehaviour older than this number of blocks. uint public constant RECENT_BLOCKS = 20; // STATE // Current list of addresses entitled to participate in the consensus. address[] public validatorsList; // Pending list of validator addresses. address[] pendingList = [0xf5777f8133aae2734396ab1d43ca54ad11bfb737]; // Tracker of status for each address. mapping(address => ValidatorStatus) validatorsStatus; // Used to lower the constructor cost. AddressVotes.Data initialSupport; // Each validator is initially supported by all others. function InnerMajoritySet() public { initialSupport.count = pendingList.length; for (uint i = 0; i < pendingList.length; i++) { address supporter = pendingList[i]; initialSupport.inserted[supporter] = true; } for (uint j = 0; j < pendingList.length; j++) { address validator = pendingList[j]; validatorsStatus[validator] = ValidatorStatus({ isValidator: true, index: j, support: initialSupport, supported: pendingList, benignMisbehaviour: AddressVotes.Data({ count: 0 }) }); } validatorsList = pendingList; } // Called on every block to update node validator list. function getValidators() public constant returns (address[]) { return validatorsList; } // Log desire to change the current list. function initiateChange() private { outerSet.initiateChange(block.blockhash(block.number - 1), pendingList); InitiateChange(block.blockhash(block.number - 1), pendingList); } function finalizeChange() public only_outer { validatorsList = pendingList; ChangeFinalized(validatorsList); } // SUPPORT LOOKUP AND MANIPULATION // Find the total support for a given address. function getSupport(address validator) public constant returns (uint) { return AddressVotes.count(validatorsStatus[validator].support); } function getSupported(address validator) public constant returns (address[]) { return validatorsStatus[validator].supported; } // Vote to include a validator. function addSupport(address validator) public only_validator not_voted(validator) free_validator_slots { newStatus(validator); AddressVotes.insert(validatorsStatus[validator].support, msg.sender); validatorsStatus[msg.sender].supported.push(validator); addValidator(validator); Support(msg.sender, validator, true); } // Remove support for a validator. function removeSupport(address sender, address validator) private { require(AddressVotes.remove(validatorsStatus[validator].support, sender)); Support(sender, validator, false); // Remove validator from the list if there is not enough support. removeValidator(validator); } // MALICIOUS BEHAVIOUR HANDLING // Called when a validator should be removed. function reportMalicious(address validator, uint blockNumber, bytes proof) public only_validator is_recent(blockNumber) { removeSupport(msg.sender, validator); Report(msg.sender, validator, true); } // BENIGN MISBEHAVIOUR HANDLING // Report that a validator has misbehaved in a benign way. function reportBenign(address validator, uint blockNumber) public only_validator is_validator(validator) is_recent(blockNumber) { firstBenign(validator); repeatedBenign(validator); Report(msg.sender, validator, false); } // Find the total number of repeated misbehaviour votes. function getRepeatedBenign(address validator) public constant returns (uint) { return AddressVotes.count(validatorsStatus[validator].benignMisbehaviour); } // Track the first benign misbehaviour. function firstBenign(address validator) private has_not_benign_misbehaved(validator) { validatorsStatus[validator].firstBenign[msg.sender] = now; } // Report that a validator has been repeatedly misbehaving. function repeatedBenign(address validator) private has_repeatedly_benign_misbehaved(validator) { AddressVotes.insert(validatorsStatus[validator].benignMisbehaviour, msg.sender); confirmedRepeatedBenign(validator); } // When enough long term benign misbehaviour votes have been seen, remove support. function confirmedRepeatedBenign(address validator) private agreed_on_repeated_benign(validator) { validatorsStatus[validator].firstBenign[msg.sender] = 0; AddressVotes.remove(validatorsStatus[validator].benignMisbehaviour, msg.sender); removeSupport(msg.sender, validator); } // Absolve a validator from a benign misbehaviour. function absolveFirstBenign(address validator) public has_benign_misbehaved(validator) { validatorsStatus[validator].firstBenign[msg.sender] = 0; AddressVotes.remove(validatorsStatus[validator].benignMisbehaviour, msg.sender); } // PRIVATE UTILITY FUNCTIONS // Add a status tracker for unknown validator. function newStatus(address validator) private has_no_votes(validator) { validatorsStatus[validator] = ValidatorStatus({ isValidator: false, index: pendingList.length, support: AddressVotes.Data({ count: 0 }), supported: new address[](0), benignMisbehaviour: AddressVotes.Data({ count: 0 }) }); } // ENACTMENT FUNCTIONS (called when support gets out of line with the validator list) // Add the validator if supported by majority. // Since the number of validators increases it is possible to some fall below the threshold. function addValidator(address validator) public is_not_validator(validator) has_high_support(validator) { validatorsStatus[validator].index = pendingList.length; pendingList.push(validator); validatorsStatus[validator].isValidator = true; // New validator should support itself. AddressVotes.insert(validatorsStatus[validator].support, validator); validatorsStatus[validator].supported.push(validator); initiateChange(); } // Remove a validator without enough support. // Can be called to clean low support validators after making the list longer. function removeValidator(address validator) public is_validator(validator) has_low_support(validator) { uint removedIndex = validatorsStatus[validator].index; // Can not remove the last validator. uint lastIndex = pendingList.length-1; address lastValidator = pendingList[lastIndex]; // Override the removed validator with the last one. pendingList[removedIndex] = lastValidator; // Update the index of the last validator. validatorsStatus[lastValidator].index = removedIndex; delete pendingList[lastIndex]; pendingList.length--; // Reset validator status. validatorsStatus[validator].index = 0; validatorsStatus[validator].isValidator = false; // Remove all support given by the removed validator. address[] storage toRemove = validatorsStatus[validator].supported; for (uint i = 0; i < toRemove.length; i++) { removeSupport(validator, toRemove[i]); } delete validatorsStatus[validator].supported; initiateChange(); } // MODIFIERS function highSupport(address validator) public constant returns (bool) { return getSupport(validator) > pendingList.length/2; } function firstBenignReported(address reporter, address validator) public constant returns (uint) { return validatorsStatus[validator].firstBenign[reporter]; } modifier has_high_support(address validator) { if (highSupport(validator)) { _; } } modifier has_low_support(address validator) { if (!highSupport(validator)) { _; } } modifier has_not_benign_misbehaved(address validator) { if (firstBenignReported(msg.sender, validator) == 0) { _; } } modifier has_benign_misbehaved(address validator) { if (firstBenignReported(msg.sender, validator) > 0) { _; } } modifier has_repeatedly_benign_misbehaved(address validator) { if (firstBenignReported(msg.sender, validator) - now > MAX_INACTIVITY) { _; } } modifier agreed_on_repeated_benign(address validator) { if (getRepeatedBenign(validator) > pendingList.length/2) { _; } } modifier free_validator_slots() { require(pendingList.length < MAX_VALIDATORS); _; } modifier only_validator() { require(validatorsStatus[msg.sender].isValidator); _; } modifier is_validator(address someone) { if (validatorsStatus[someone].isValidator) { _; } } modifier is_not_validator(address someone) { if (!validatorsStatus[someone].isValidator) { _; } } modifier not_voted(address validator) { require(!AddressVotes.contains(validatorsStatus[validator].support, msg.sender)); _; } modifier has_no_votes(address validator) { if (AddressVotes.count(validatorsStatus[validator].support) == 0) { _; } } modifier is_recent(uint blockNumber) { require(block.number <= blockNumber + RECENT_BLOCKS); _; } }
Vote to include a validator.
function addSupport(address validator) public only_validator not_voted(validator) free_validator_slots { newStatus(validator); AddressVotes.insert(validatorsStatus[validator].support, msg.sender); validatorsStatus[msg.sender].supported.push(validator); addValidator(validator); Support(msg.sender, validator, true); }
1,041,071
[ 1, 19338, 358, 2341, 279, 4213, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 527, 6289, 12, 2867, 4213, 13, 1071, 1338, 67, 7357, 486, 67, 90, 16474, 12, 7357, 13, 4843, 67, 7357, 67, 18875, 288, 203, 202, 202, 2704, 1482, 12, 7357, 1769, 203, 202, 202, 1887, 29637, 18, 6387, 12, 23993, 1482, 63, 7357, 8009, 13261, 16, 1234, 18, 15330, 1769, 203, 202, 202, 23993, 1482, 63, 3576, 18, 15330, 8009, 4127, 18, 6206, 12, 7357, 1769, 203, 202, 202, 1289, 5126, 12, 7357, 1769, 203, 202, 202, 6289, 12, 3576, 18, 15330, 16, 4213, 16, 638, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import { BlindDrop } from "./BlindDrop.sol"; import { Base64 } from "./Base64.sol"; import { ERC721EnumerableOptimized } from "./ERC721EnumerableOptimized.sol"; import { FlootConstants } from "./FlootConstants.sol"; /** * @title FlootMetadata * @author the-torn * * @notice Logic for generating metadata, including the SVG graphic with text. * * Based closely on the original Loot implementation (MIT License). * https://etherscan.io/address/0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7#code#L1 */ abstract contract FlootMetadata is BlindDrop, ERC721EnumerableOptimized { function random( string memory input ) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getWeapon( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.WEAPON); } function getChest( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.CHEST); } function getHead( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.HEAD); } function getWaist( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.WAIST); } function getFoot( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.FOOT); } function getHand( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.HAND); } function getNeck( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.NECK); } function getRing( uint256 tokenId ) public view returns (string memory) { return pluck(tokenId, FlootConstants.ListName.RING); } function pluck( uint256 tokenId, FlootConstants.ListName keyPrefix ) internal view returns (string memory) { // Get the blind drop seed. Will revert if the distribution is not complete or if the seed // has not yet been finalized. bytes32 seed = getFinalSeed(); // On-chain randomness. string memory inputForRandomness = string(abi.encodePacked( keyPrefix, tokenId, // Note: No need to use toString() here. seed )); uint256 rand = random(inputForRandomness); // Determine the item name based on the randomly generated number. string memory output = FlootConstants.getItem(rand, keyPrefix); uint256 greatness = rand % 21; if (greatness > 14) { output = string(abi.encodePacked(output, " ", FlootConstants.getItem(rand, FlootConstants.ListName.SUFFIX))); } if (greatness >= 19) { string[2] memory name; name[0] = FlootConstants.getItem(rand, FlootConstants.ListName.NAME_PREFIX); name[1] = FlootConstants.getItem(rand, FlootConstants.ListName.NAME_SUFFIX); if (greatness == 19) { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output)); } else { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1")); } } return output; } function tokenURI( uint256 tokenId ) override public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getWeapon(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getChest(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getHead(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getWaist(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getFoot(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getHand(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getNeck(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; parts[15] = getRing(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16])); string memory json = Base64.encode(bytes(string(abi.encodePacked( '{"name": "Bag #', FlootConstants.toString(tokenId), '", "description": "Floot is randomized adventurer gear generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Floot in any way you want.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}' )))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } }
Get the blind drop seed. Will revert if the distribution is not complete or if the seed has not yet been finalized. On-chain randomness. Determine the item name based on the randomly generated number.
function pluck( uint256 tokenId, FlootConstants.ListName keyPrefix ) internal view returns (string memory) { bytes32 seed = getFinalSeed(); string memory inputForRandomness = string(abi.encodePacked( keyPrefix, seed )); uint256 rand = random(inputForRandomness); string memory output = FlootConstants.getItem(rand, keyPrefix); uint256 greatness = rand % 21; if (greatness > 14) { output = string(abi.encodePacked(output, " ", FlootConstants.getItem(rand, FlootConstants.ListName.SUFFIX))); } if (greatness >= 19) { string[2] memory name; name[0] = FlootConstants.getItem(rand, FlootConstants.ListName.NAME_PREFIX); name[1] = FlootConstants.getItem(rand, FlootConstants.ListName.NAME_SUFFIX); if (greatness == 19) { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output)); output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1")); } } return output; }
15,803,411
[ 1, 967, 326, 29696, 3640, 5009, 18, 9980, 15226, 309, 326, 7006, 353, 486, 3912, 578, 309, 326, 5009, 711, 486, 4671, 2118, 727, 1235, 18, 2755, 17, 5639, 2744, 4496, 18, 10229, 326, 761, 508, 2511, 603, 326, 20153, 4374, 1300, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 16976, 12, 203, 565, 2254, 5034, 1147, 548, 16, 203, 565, 478, 383, 352, 2918, 18, 682, 461, 28877, 203, 225, 262, 203, 565, 2713, 203, 565, 1476, 203, 565, 1135, 261, 1080, 3778, 13, 203, 225, 288, 203, 565, 1731, 1578, 5009, 273, 2812, 1490, 12702, 5621, 203, 203, 565, 533, 3778, 810, 1290, 8529, 4496, 273, 533, 12, 21457, 18, 3015, 4420, 329, 12, 203, 1377, 28877, 16, 203, 1377, 5009, 203, 565, 262, 1769, 203, 565, 2254, 5034, 5605, 273, 2744, 12, 2630, 1290, 8529, 4496, 1769, 203, 203, 565, 533, 3778, 876, 273, 478, 383, 352, 2918, 18, 588, 1180, 12, 7884, 16, 28877, 1769, 203, 565, 2254, 5034, 18825, 4496, 273, 5605, 738, 9035, 31, 203, 565, 309, 261, 75, 6150, 4496, 405, 5045, 13, 288, 203, 1377, 876, 273, 533, 12, 21457, 18, 3015, 4420, 329, 12, 2844, 16, 315, 3104, 478, 383, 352, 2918, 18, 588, 1180, 12, 7884, 16, 478, 383, 352, 2918, 18, 682, 461, 18, 14964, 3719, 1769, 203, 565, 289, 203, 565, 309, 261, 75, 6150, 4496, 1545, 5342, 13, 288, 203, 1377, 533, 63, 22, 65, 3778, 508, 31, 203, 1377, 508, 63, 20, 65, 273, 478, 383, 352, 2918, 18, 588, 1180, 12, 7884, 16, 478, 383, 352, 2918, 18, 682, 461, 18, 1985, 67, 6307, 1769, 203, 1377, 508, 63, 21, 65, 273, 478, 383, 352, 2918, 18, 588, 1180, 12, 7884, 16, 478, 383, 352, 2918, 18, 682, 461, 18, 1985, 67, 14964, 1769, 203, 1377, 309, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; import "./announcement.sol"; import "./eventsEIP1129.sol"; import "https://github.com/vigilance91/solidarity/libraries/unsigned/uint256ToString.sol"; /// /// @dev Library for managing an enumerable mapping of Announcements /// Maps have the following properties: /// /// - Entries are added, removed, and checked for existence in constant time (O(1)) /// - Entries are enumerated in O(n) /// - No guarantees are made on element ordering /// library EnumerableAnnouncementMap { using SafeMath for uint256; using uint256Logic for uint256; using uint256Constraints for uint256; using uint256ToString for uint256; using addressToString for address; using stringUtilities for string; using eventsEIP1129Announcements for bytes32; //uint256 private constant SENTINEL = 0; struct MapEntry { bytes32 _key; announcement.data _value; } // Storage of map keys and values struct Map { MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32=>uint256) _indexes; } function indexForKey( Map storage map, bytes32 key )internal view returns( uint256 ){ return map._indexes[key]; } function keyForIndex( Map storage map, uint256 index )internal view returns( bytes32 ){ uint256 L = _length(map); L.requireGreaterThanZero(); index.requireLessThan(L); return map._entries[index]._key; } /// /// @dev Adds a key-value pair to a map or, /// updates the value for an existing key, O(1) /// /// @return {bool} true if the key was added to the map, /// if it was not already present /// function initialize( Map storage map, //bytes32 key, //announcement.data memory value address author, string memory authorName, string memory message )public returns( bool ){ //string authorName = VSN_METADATA_REGISTRY.getAuthorName(address); string memory HEX = author.hexadecimal(); bytes32 msgHash = HEX.saltAndHash(message); bytes32 authorHash = HEX.saltAndHash(authorName); bytes32 key = keccak256(bytes(block.number.hexadecimal())); // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to !contains(map, key) if(keyIndex.notEqual(0)){ return false; } map._entries.push(MapEntry({ _key: key, _value: announcement.data( authorHash, //unique hash, used to verify the author and/or platform msgHash, //unique hash, used to verify the message integrity authorName, message, now, block.number ) })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; key.emitNewAnnouncement( authorHash, msgHash, //authorName, message ); return true; } ///reset a previously set post function edit( Map storage map, bytes32 key, //announcement.data memory value address author, string memory authorName, string memory message, string memory reason )public returns( bool ){ uint256 keyIndex = map._indexes[key]; // Equivalent to !contains(map, key) keyIndex.requireGreaterThanZero( ); //string authorName = VSN_METADATA_REGISTRY.getAuthorName(address); string memory HEX = author.hexadecimal(); bytes32 msgHash = HEX.saltAndHash(message); bytes32 authorHash = HEX.saltAndHash(authorName); // We read and store the key's index to prevent multiple reads from the same storage slot map._entries[keyIndex.sub(1)]._value = announcement.data( authorHash, //unique hash, used to verify the author and/or platform msgHash, //unique hash, used to verify the message integrity authorName, message, now, block.number ); key.emitEditAnnouncement( authorHash, msgHash, message, reason ); return true; } /** /// @return {announcement.data[]} an array containing a subset (slice) of the primary storage /// @dev calling this may become prohabitively expensive for large ranges, /// since loops in Ethereum consume large quantities of gas function slice( Map storage map, uint256 indexStart, uint256 indexStop )public returns( announcement.data[] memory ret ){ uint256 L = _length(map); L.requireGreaterThanZero( ); L.requireGreaterThanOrEqual(indexStop); for(uint256 i = indexStart; i < indexStop; i++){ ret.push(at(map,i)); } } */ //function _swap( //uint256 firstIndex, //uint256 secondIndex //)private //{ //uint256 toDeleteIndex = firstIndex - 1; //uint256 lastIndex = secondIndex - 1; //MapEntry storage lastEntry = map._entries[lastIndex]; //// swap the last entry with the index where the entry to be deleted is //map._entries[toDeleteIndex] = lastEntry; //// Update the index for the moved entry //map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based //} /// /// @dev Removes a key-value pair from a map, O(1) /// @return {bool} true if key was removed from map, if it was present /// function remove( Map storage map, bytes32 key, bytes32 removerHash, string memory reason )public returns( bool ){ // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to contains(map, key) if(keyIndex.equal(0)){ return false; } // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at} //_swap( //keyIndex, //map._entries.length.sub(1) //); uint256 toDeleteIndex = keyIndex.sub(1); uint256 lastIndex = map._entries.length.sub(1); // When the entry to delete is the last one, the swap operation is unnecessary. // However, since this occurs so rarely, perform the swap anyway to avoid the gas cost of adding an 'if' statement MapEntry storage lastEntry = map._entries[lastIndex]; MapEntry storage toRemove = map._entries[toDeleteIndex]; // swap the last entry with the index where the entry to be deleted is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex.add(1); // All indexes are 1-based toRemove._key.emitRemovedAnnouncement( toRemove._value.authorHash, toRemove._value.postHash, //toRemove._value.post, reason, removerHash ); // Delete the slot where the moved entry was stored map._entries.pop(); delete map._indexes[key]; return true; } /// @return {bool} true if the key is in the map, O(1) function contains( Map storage map, bytes32 key )public view returns( bool ){ return map._indexes[key] != 0; } /// @return {uint256} number of key-value pairs in the map, time complexity O(1) function _length( Map storage map )internal view returns( uint256 ){ return map._entries.length; } /// /// @return {bytes32, bytes32} the key-value pair stored at position `index` in the map, O(1) /// /// Note that there are no guarantees on the ordering of entries inside the array, /// and it may change when more entries are added or removed /// /// Requirements: /// - `index` must be strictly less than {length} /// function at( Map storage map, uint256 index )public view returns( bytes32, announcement.data memory ){ map._entries.length.requireGreaterThan( index //"index out of bounds" ); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /// /// @return {bytes32} the value associated with `key`, O(1) /// /// Requirements: /// - `key` must be in the map /// function _get( Map storage map, bytes32 key )private view returns( announcement.data memory ){ return _get( map, key, "EnumerableMap: nonexistent key" ); } /// @dev Same as {_get}, with a custom error message when `key` is not in the map function _get( Map storage map, bytes32 key, string memory errorMessage )private view returns( announcement.data memory ){ //map._entries.length.requireGreaterThan(0); uint256 keyIndex = map._indexes[key]; // Equivalent to contains(map, key) keyIndex.requireNotEqual( 0 //errorMessage ); map._entries.length.requireGreaterThan( keyIndex //"EnumerableMap: index out of bounds" ); //note all indexes are 1-based return map._entries[keyIndex.sub(1)]._value; } }
swap the last entry with the index where the entry to be deleted is
map._entries[toDeleteIndex] = lastEntry;
12,573,370
[ 1, 22270, 326, 1142, 1241, 598, 326, 770, 1625, 326, 1241, 358, 506, 4282, 353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 852, 6315, 8219, 63, 869, 2613, 1016, 65, 273, 1142, 1622, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; /* ___ ___ ___ ___ ___ /\ \ /\__\ /\ \ /\ \ /\ \ /::\ \ /:/ _/_ /::\ \ _\:\ \ \:\ \ \:\:\__\ /:/_/\__\ /::\:\__\ /\/::\__\ /::\__\ \::/ / \:\/:/ / \:\::/ / \::/\/__/ /:/\/__/ /:/ / \::/ / \::/ / \:\__\ \/__/ \/__/ \/__/ \/__/ \/__/ * * MIT License * =========== * * Copyright (c) 2021 QubitFinance * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/IPriceCalculator.sol"; import "../interfaces/IQToken.sol"; import "../interfaces/IQore.sol"; import "../interfaces/IDashboard.sol"; import "../interfaces/IQubitLocker.sol"; import "../interfaces/IBEP20.sol"; contract DashboardBSC is IDashboard, OwnableUpgradeable { using SafeMath for uint; /* ========== CONSTANT VARIABLES ========== */ address private constant QBT = 0x17B7163cf1Dbd286E262ddc68b553D899B93f526; IPriceCalculator public constant priceCalculator = IPriceCalculator(0x20E5E35ba29dC3B540a1aee781D0814D5c77Bce6); /* ========== STATE VARIABLES ========== */ IQore public qore; IQubitLocker public qubitLocker; /* ========== INITIALIZER ========== */ function initialize() external initializer { __Ownable_init(); } /* ========== RESTRICTED FUNCTIONS ========== */ function setQore(address _qore) external onlyOwner { require(_qore != address(0), "DashboardBSC: invalid qore address"); require(address(qore) == address(0), "DashboardBSC: qore already set"); qore = IQore(_qore); } function setLocker(address _qubitLocker) external onlyOwner { require(_qubitLocker != address(0), "DashboardBSC: invalid locker address"); qubitLocker = IQubitLocker(_qubitLocker); } /* ========== VIEW FUNCTIONS ========== */ function qubitDataOf(address[] memory markets, address account) public view override returns (QubitData memory) { QubitData memory qubit; qubit.marketList = new MarketData[](markets.length); qubit.membershipList = new MembershipData[](markets.length); if (account != address(0)) { qubit.accountAcc = accountAccDataOf(account); qubit.locker = lockerDataOf(account); } for (uint i = 0; i < markets.length; i++) { qubit.marketList[i] = marketDataOf(markets[i]); if (account != address(0)) { qubit.membershipList[i] = membershipDataOf(markets[i], account); } } qubit.marketAverageBoostedRatio = _calculateAccMarketAverageBoostedRatio(markets); return qubit; } function marketDataOf(address market) public view override returns (MarketData memory) { MarketData memory marketData; QConstant.DistributionAPY memory apyDistribution = qore.apyDistributionOf(market, address(0)); QConstant.DistributionInfo memory distributionInfo = qore.distributionInfoOf(market); IQToken qToken = IQToken(market); marketData.qToken = market; marketData.apySupply = qToken.supplyRatePerSec().mul(365 days); marketData.apyBorrow = qToken.borrowRatePerSec().mul(365 days); marketData.apySupplyQBT = apyDistribution.apySupplyQBT; marketData.apyBorrowQBT = apyDistribution.apyBorrowQBT; marketData.totalSupply = qToken.totalSupply().mul(qToken.exchangeRate()).div(1e18); marketData.totalBorrows = qToken.totalBorrow(); marketData.totalBoostedSupply = distributionInfo.totalBoostedSupply; marketData.totalBoostedBorrow = distributionInfo.totalBoostedBorrow; marketData.cash = qToken.getCash(); marketData.reserve = qToken.totalReserve(); marketData.reserveFactor = qToken.reserveFactor(); marketData.collateralFactor = qore.marketInfoOf(market).collateralFactor; marketData.exchangeRate = qToken.exchangeRate(); marketData.borrowCap = qore.marketInfoOf(market).borrowCap; marketData.accInterestIndex = qToken.getAccInterestIndex(); return marketData; } function membershipDataOf(address market, address account) public view override returns (MembershipData memory) { MembershipData memory membershipData; QConstant.DistributionAPY memory apyDistribution = qore.apyDistributionOf(market, account); QConstant.DistributionAccountInfo memory accountDistributionInfo = qore.accountDistributionInfoOf(market, account); membershipData.qToken = market; membershipData.membership = qore.checkMembership(account, market); membershipData.supply = IQToken(market).underlyingBalanceOf(account); membershipData.borrow = IQToken(market).borrowBalanceOf(account); membershipData.boostedSupply = accountDistributionInfo.boostedSupply; membershipData.boostedBorrow = accountDistributionInfo.boostedBorrow; membershipData.apyAccountSupplyQBT = apyDistribution.apyAccountSupplyQBT; membershipData.apyAccountBorrowQBT = apyDistribution.apyAccountBorrowQBT; return membershipData; } function accountAccDataOf(address account) public view override returns (AccountAccData memory) { AccountAccData memory accData; accData.accruedQubit = qore.accruedQubit(account); (accData.collateralInUSD,, accData.borrowInUSD) = qore.accountLiquidityOf(account); address[] memory markets = qore.allMarkets(); uint[] memory prices = priceCalculator.getUnderlyingPrices(markets); for (uint i = 0; i < markets.length; i++) { accData.supplyInUSD = accData.supplyInUSD.add(IQToken(markets[i]).underlyingBalanceOf(account).mul(prices[i]).div(1e18)); } uint totalValueInUSD = accData.supplyInUSD.add(accData.borrowInUSD); (accData.accApySupply, accData.accApySupplyQBT) = _calculateAccAccountSupplyAPYOf(account, markets, prices, totalValueInUSD); (accData.accApyBorrow, accData.accApyBorrowQBT) = _calculateAccAccountBorrowAPYOf(account, markets, prices, totalValueInUSD); accData.averageBoostedRatio = _calculateAccAccountAverageBoostedRatio(account, markets); return accData; } function lockerDataOf(address account) public view override returns (LockerData memory) { LockerData memory lockerInfo; lockerInfo.totalLocked = qubitLocker.totalBalance(); lockerInfo.locked = qubitLocker.balanceOf(account); (uint totalScore, ) = qubitLocker.totalScore(); lockerInfo.totalScore = totalScore; lockerInfo.score = qubitLocker.scoreOf(account); lockerInfo.available = qubitLocker.availableOf(account); lockerInfo.expiry = qubitLocker.expiryOf(account); return lockerInfo; } function totalValueLockedOf(address[] memory markets) public view returns (uint totalSupplyInUSD) { uint[] memory prices = priceCalculator.getUnderlyingPrices(markets); for (uint i = 0; i < markets.length; i++) { uint supplyInUSD = IQToken(markets[i]).getCash().mul(IQToken(markets[i]).exchangeRate()).div(1e18); totalSupplyInUSD = totalSupplyInUSD.add(supplyInUSD.mul(prices[i]).div(1e18)); } return totalSupplyInUSD; } function totalCirculating() public view returns (uint) { return IBEP20(QBT).totalSupply() .sub(IBEP20(QBT).balanceOf(0xa7bc9a205A46017F47949F5Ee453cEBFcf42121b)) // reward Lock .sub(IBEP20(QBT).balanceOf(0xB224eD67C2F89Ae97758a9DB12163A6f30830EB2)) // developer's Supply Lock .sub(IBEP20(QBT).balanceOf(0x4c97c901B5147F8C1C7Ce3c5cF3eB83B44F244fE)) // MND Vault Lock .sub(IBEP20(QBT).balanceOf(0xB56290bEfc4216dc2A526a9022A76A1e4FDf122b)) // marketing Treasury .sub(IBEP20(QBT).balanceOf(0xAAf5d0dB947F835287b9432F677A51e9a1a01a35)) // security Treasury .sub(IBEP20(QBT).balanceOf(0xc7939B1Fa2E7662592b4d11dbE3C331bEE18FC85)) // Dev Treasury // .sub(qubitLocker.balanceOf(0x12C62464D8CF4a9Ca6f2EEAd1d7954A9fC21d053)) // QubitPool (lock forever) .sub(qubitLocker.totalBalance()) // QubitLocker .sub(IBEP20(QBT).balanceOf(0x67B806ab830801348ce719E0705cC2f2718117a1)) // reward Distributor (QDistributor) .sub(IBEP20(QBT).balanceOf(0xD1ad1943b70340783eD9814ffEdcAaAe459B6c39)) // PCB QBT-BNB pool reward lock .sub(IBEP20(QBT).balanceOf(0x89c527764f03BCb7dC469707B23b79C1D7Beb780)); // Orbit Bridge lock (displayed in Klaytn instead) } /* ========== PRIVATE FUNCTIONS ========== */ function _calculateAccAccountSupplyAPYOf(address account, address[] memory markets, uint[] memory prices, uint totalValueInUSD) private view returns (uint accApySupply, uint accApySupplyQBT) { for (uint i = 0; i < markets.length; i++) { QConstant.DistributionAPY memory apyDistribution = qore.apyDistributionOf(markets[i], account); uint supplyInUSD = IQToken(markets[i]).underlyingBalanceOf(account).mul(prices[i]).div(1e18); accApySupply = accApySupply.add(supplyInUSD.mul(IQToken(markets[i]).supplyRatePerSec().mul(365 days)).div(1e18)); accApySupplyQBT = accApySupplyQBT.add(supplyInUSD.mul(apyDistribution.apyAccountSupplyQBT).div(1e18)); } accApySupply = totalValueInUSD > 0 ? accApySupply.mul(1e18).div(totalValueInUSD) : 0; accApySupplyQBT = totalValueInUSD > 0 ? accApySupplyQBT.mul(1e18).div(totalValueInUSD) : 0; } function _calculateAccAccountBorrowAPYOf(address account, address[] memory markets, uint[] memory prices, uint totalValueInUSD) private view returns (uint accApyBorrow, uint accApyBorrowQBT) { for (uint i = 0; i < markets.length; i++) { QConstant.DistributionAPY memory apyDistribution = qore.apyDistributionOf(markets[i], account); uint borrowInUSD = IQToken(markets[i]).borrowBalanceOf(account).mul(prices[i]).div(1e18); accApyBorrow = accApyBorrow.add(borrowInUSD.mul(IQToken(markets[i]).borrowRatePerSec().mul(365 days)).div(1e18)); accApyBorrowQBT = accApyBorrowQBT.add(borrowInUSD.mul(apyDistribution.apyAccountBorrowQBT).div(1e18)); } accApyBorrow = totalValueInUSD > 0 ? accApyBorrow.mul(1e18).div(totalValueInUSD) : 0; accApyBorrowQBT = totalValueInUSD > 0 ? accApyBorrowQBT.mul(1e18).div(totalValueInUSD) : 0; } function _calculateAccAccountAverageBoostedRatio(address account, address[] memory markets) public view returns (uint averageBoostedRatio) { uint accBoostedCount = 0; for (uint i = 0; i < markets.length; i++) { (uint boostedSupplyRatio, uint boostedBorrowRatio) = qore.boostedRatioOf(markets[i], account); if (boostedSupplyRatio > 0) { averageBoostedRatio = averageBoostedRatio.add(boostedSupplyRatio); accBoostedCount++; } if (boostedBorrowRatio > 0) { averageBoostedRatio = averageBoostedRatio.add(boostedBorrowRatio); accBoostedCount++; } } return accBoostedCount > 0 ? averageBoostedRatio.div(accBoostedCount) : 0; } function _calculateAccMarketAverageBoostedRatio(address[] memory markets) public view returns (uint averageBoostedRatio) { uint accValueInUSD = 0; uint accBoostedValueInUSD = 0; uint[] memory prices = priceCalculator.getUnderlyingPrices(markets); for (uint i = 0; i < markets.length; i++) { QConstant.DistributionInfo memory distributionInfo = qore.distributionInfoOf(markets[i]); accBoostedValueInUSD = accBoostedValueInUSD.add(distributionInfo.totalBoostedSupply.mul(IQToken(markets[i]).exchangeRate()).mul(prices[i]).div(1e36)); accBoostedValueInUSD = accBoostedValueInUSD.add(distributionInfo.totalBoostedBorrow.mul(IQToken(markets[i]).getAccInterestIndex()).mul(prices[i]).div(1e36)); accValueInUSD = accValueInUSD.add(IQToken(markets[i]).totalSupply().mul(IQToken(markets[i]).exchangeRate()).mul(prices[i]).div(1e36)); accValueInUSD = accValueInUSD.add(IQToken(markets[i]).totalBorrow().mul(prices[i]).div(1e18)); } return accValueInUSD > 0 ? accBoostedValueInUSD.mul(1e18).div(accValueInUSD) : 0; } }
.sub(qubitLocker.balanceOf(0x12C62464D8CF4a9Ca6f2EEAd1d7954A9fC21d053)) QubitPool (lock forever)
function totalCirculating() public view returns (uint) { return IBEP20(QBT).totalSupply() }
12,837,321
[ 1, 18, 1717, 12, 372, 3682, 2531, 264, 18, 12296, 951, 12, 20, 92, 2138, 39, 26, 3247, 1105, 40, 28, 8955, 24, 69, 29, 23508, 26, 74, 22, 9383, 1871, 21, 72, 7235, 6564, 37, 29, 74, 39, 5340, 72, 6260, 23, 3719, 4202, 2238, 373, 305, 2864, 261, 739, 21238, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 10887, 1934, 1776, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 467, 5948, 52, 3462, 12, 53, 38, 56, 2934, 4963, 3088, 1283, 1435, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; // This is only kept for backward compatability / upgrading import {OwnableUpgradeable} from "../oz/access/OwnableUpgradeable.sol"; import {EnumerableMapUpgradeable, ERC721PausableUpgradeable, IERC721Upgradeable, ERC721Upgradeable} from "../oz/token/ERC721/ERC721PausableUpgradeable.sol"; import {IRegistrar} from "../interfaces/IRegistrar.sol"; import {StorageSlot} from "../oz/utils/StorageSlot.sol"; import {BeaconProxy} from "../oz/proxy/beacon/BeaconProxy.sol"; import {IZNSHub} from "../interfaces/IZNSHub.sol"; contract Registrar is IRegistrar, OwnableUpgradeable, ERC721PausableUpgradeable { using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; // Data recorded for each domain struct DomainRecord { address minter; bool metadataLocked; address metadataLockedBy; address controller; uint256 royaltyAmount; uint256 parentId; address subdomainContract; } // A map of addresses that are authorised to register domains. mapping(address => bool) public controllers; // A mapping of domain id's to domain data // This essentially expands the internal ERC721's token storage to additional fields mapping(uint256 => DomainRecord) public records; /** * @dev Storage slot with the admin of the contract. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; // The beacon address address public beacon; // If this is a subdomain contract these will be set uint256 public rootDomainId; address public parentRegistrar; // The event emitter IZNSHub public zNSHub; uint8 private test; // ignore uint256 private gap; // ignore function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } modifier onlyController() { if (!controllers[msg.sender] && !zNSHub.isController(msg.sender)) { revert("ZR: Not controller"); } _; } modifier onlyOwnerOf(uint256 id) { require(ownerOf(id) == msg.sender, "ZR: Not owner"); _; } function initialize( address parentRegistrar_, uint256 rootDomainId_, string calldata collectionName, string calldata collectionSymbol, address zNSHub_ ) public initializer { // __Ownable_init(); // Purposely not initializing ownable since we override owner() if (parentRegistrar_ == address(0)) { // create the root domain _createDomain(0, 0, msg.sender, address(0)); } else { rootDomainId = rootDomainId_; parentRegistrar = parentRegistrar_; } zNSHub = IZNSHub(zNSHub_); __ERC721Pausable_init(); __ERC721_init(collectionName, collectionSymbol); } // Used to upgrade existing registrar to new registrar function upgradeFromNormalRegistrar(address zNSHub_) public { require(msg.sender == _getAdmin(), "Not Proxy Admin"); zNSHub = IZNSHub(zNSHub_); } function owner() public view override returns (address) { return zNSHub.owner(); } /* * External Methods */ /** * @notice Authorizes a controller to control the registrar * @param controller The address of the controller */ function addController(address controller) external { require( msg.sender == owner() || msg.sender == parentRegistrar, "ZR: Not authorized" ); require(!controllers[controller], "ZR: Controller is already added"); controllers[controller] = true; emit ControllerAdded(controller); } /** * @notice Unauthorizes a controller to control the registrar * @param controller The address of the controller */ function removeController(address controller) external override onlyOwner { require( msg.sender == owner() || msg.sender == parentRegistrar, "ZR: Not authorized" ); require(controllers[controller], "ZR: Controller does not exist"); controllers[controller] = false; emit ControllerRemoved(controller); } /** * @notice Pauses the registrar. Can only be done when not paused. */ function pause() external onlyOwner { _pause(); } /** * @notice Unpauses the registrar. Can only be done when not paused. */ function unpause() external onlyOwner { _unpause(); } /** * @notice Registers a new (sub) domain * @param parentId The parent domain * @param label The label of the domain * @param minter the minter of the new domain * @param metadataUri The uri of the metadata * @param royaltyAmount The amount of royalty this domain pays * @param locked Whether the domain is locked or not */ function registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) external override onlyController returns (uint256) { return _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); } function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external override onlyController returns (uint256) { // Register the domain uint256 id = _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); // immediately send domain to user _safeTransfer(minter, sendToUser, id, ""); return id; } function registerSubdomainContract( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external onlyController returns (uint256) { // Register domain, `minter` is the minter uint256 id = _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); // Create subdomain contract as a beacon proxy address subdomainContract = address( new BeaconProxy(zNSHub.registrarBeacon(), "") ); // More maintainable instead of using `data` in constructor Registrar(subdomainContract).initialize( address(this), id, "Zer0 Name Service", "ZNS", address(zNSHub) ); // Indicate that the subdomain has a contract records[id].subdomainContract = subdomainContract; zNSHub.addRegistrar(id, subdomainContract); // immediately send the domain to the user (from the minter) _safeTransfer(minter, sendToUser, id, ""); return id; } function _registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) internal returns (uint256) { require(bytes(label).length > 0, "ZR: Empty name"); // subdomain cannot be minted on domains which are subdomain contracts require( records[parentId].subdomainContract == address(0), "ZR: Parent is subcontract" ); if (parentId != rootDomainId) { // Domain parents must exist require(_exists(parentId), "ZR: No parent"); } // Create the child domain under the parent domain uint256 labelHash = uint256(keccak256(bytes(label))); address controller = msg.sender; // Calculate the new domain's id and create it uint256 domainId = uint256( keccak256(abi.encodePacked(parentId, labelHash)) ); _createDomain(parentId, domainId, minter, controller); _setTokenURI(domainId, metadataUri); if (locked) { records[domainId].metadataLockedBy = minter; records[domainId].metadataLocked = true; } if (royaltyAmount > 0) { records[domainId].royaltyAmount = royaltyAmount; } zNSHub.domainCreated( domainId, label, labelHash, parentId, minter, controller, metadataUri, royaltyAmount ); return domainId; } /** * @notice Sets the domain royalty amount * @param id The domain to set on * @param amount The royalty amount */ function setDomainRoyaltyAmount(uint256 id, uint256 amount) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); records[id].royaltyAmount = amount; zNSHub.royaltiesAmountChanged(id, amount); } /** * @notice Both sets and locks domain metadata uri in a single call * @param id The domain to lock * @param uri The uri to set */ function setAndLockDomainMetadata(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); _setDomainMetadataUri(id, uri); _setDomainLock(id, msg.sender, true); } /** * @notice Sets the domain metadata uri * @param id The domain to set on * @param uri The uri to set */ function setDomainMetadataUri(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); _setDomainMetadataUri(id, uri); } /** * @notice Locks a domains metadata uri * @param id The domain to lock * @param toLock whether the domain should be locked or not */ function lockDomainMetadata(uint256 id, bool toLock) external override { _validateLockDomainMetadata(id, toLock); _setDomainLock(id, msg.sender, toLock); } /* * Public View */ function ownerOf(uint256 tokenId) public view virtual override(ERC721Upgradeable, IERC721Upgradeable) returns (address) { // Check if the token is in this contract if (_tokenOwners.contains(tokenId)) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } return zNSHub.ownerOf(tokenId); } /** * @notice Returns whether or not an account is a a controller registered on this contract * @param account Address of account to check */ function isController(address account) external view override returns (bool) { bool accountIsController = controllers[account]; return accountIsController; } /** * @notice Returns whether or not a domain is exists * @param id The domain */ function domainExists(uint256 id) public view override returns (bool) { bool domainNftExists = _exists(id); return domainNftExists; } /** * @notice Returns the original minter of a domain * @param id The domain */ function minterOf(uint256 id) public view override returns (address) { address minter = records[id].minter; return minter; } /** * @notice Returns whether or not a domain's metadata is locked * @param id The domain */ function isDomainMetadataLocked(uint256 id) public view override returns (bool) { bool isLocked = records[id].metadataLocked; return isLocked; } /** * @notice Returns who locked a domain's metadata * @param id The domain */ function domainMetadataLockedBy(uint256 id) public view override returns (address) { address lockedBy = records[id].metadataLockedBy; return lockedBy; } /** * @notice Returns the controller which created the domain on behalf of a user * @param id The domain */ function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; } /** * @notice Returns the current royalty amount for a domain * @param id The domain */ function domainRoyaltyAmount(uint256 id) public view override returns (uint256) { uint256 amount = records[id].royaltyAmount; return amount; } /** * @notice Returns the parent id of a domain. * @param id The domain */ function parentOf(uint256 id) public view override returns (uint256) { require(_exists(id), "ZR: Does not exist"); uint256 parentId = records[id].parentId; return parentId; } /* * Internal Methods */ function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); // Need to emit transfer events on event emitter zNSHub.domainTransferred(from, to, tokenId); } function _setDomainMetadataUri(uint256 id, string memory uri) internal { _setTokenURI(id, uri); zNSHub.metadataChanged(id, uri); } function _validateLockDomainMetadata(uint256 id, bool toLock) internal view { if (toLock) { require(ownerOf(id) == msg.sender, "ZR: Not owner"); require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); } else { require(isDomainMetadataLocked(id), "ZR: Not locked"); require(domainMetadataLockedBy(id) == msg.sender, "ZR: Not locker"); } } // internal - creates a domain function _createDomain( uint256 parentId, uint256 domainId, address minter, address controller ) internal { // Create the NFT and register the domain data _mint(minter, domainId); records[domainId] = DomainRecord({ parentId: parentId, minter: minter, metadataLocked: false, metadataLockedBy: address(0), controller: controller, royaltyAmount: 0, subdomainContract: address(0) }); } function _setDomainLock( uint256 id, address locker, bool lockStatus ) internal { records[id].metadataLockedBy = locker; records[id].metadataLocked = lockStatus; zNSHub.metadataLockChanged(id, locker, lockStatus); } function adminBurnToken(uint256 tokenId) external onlyOwner { _burn(tokenId); delete (records[tokenId]); } function adminTransfer( address from, address to, uint256 tokenId ) external onlyOwner { _transfer(from, to, tokenId); } function adminSetMetadataUri(uint256 id, string memory uri) external onlyOwner { _setDomainMetadataUri(id, uri); } function registerDomainAndSendBulk( uint256 parentId, uint256 namingOffset, // e.g., the IPFS node refers to the metadata as x. the zNS label will be x + namingOffset uint256 startingIndex, uint256 endingIndex, address minter, string memory folderWithIPFSPrefix, // e.g., ipfs://Qm.../ uint256 royaltyAmount, bool locked ) external onlyController { require(endingIndex - startingIndex > 0, "Invalid number of domains"); uint256 result; for (uint256 i = startingIndex; i < endingIndex; i++) { result = _registerDomain( parentId, uint2str(i + namingOffset), minter, string(abi.encodePacked(folderWithIPFSPrefix, uint2str(i))), royaltyAmount, locked ); } } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ERC721Upgradeable.sol"; import "../../utils/PausableUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer {} /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../oz/token/ERC721/IERC721EnumerableUpgradeable.sol"; import "../oz/token/ERC721/IERC721MetadataUpgradeable.sol"; interface IRegistrar is IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { // Emitted when a controller is removed event ControllerAdded(address indexed controller); // Emitted whenever a controller is removed event ControllerRemoved(address indexed controller); // Emitted whenever a new domain is created event DomainCreated( uint256 indexed id, string label, uint256 indexed labelHash, uint256 indexed parent, address minter, address controller, string metadataUri, uint256 royaltyAmount ); // Emitted whenever the metadata of a domain is locked event MetadataLockChanged(uint256 indexed id, address locker, bool isLocked); // Emitted whenever the metadata of a domain is changed event MetadataChanged(uint256 indexed id, string uri); // Emitted whenever the royalty amount is changed event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount); // Authorises a controller, who can register domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Registers a new sub domain function registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) external returns (uint256); function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); function registerSubdomainContract( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); // Set a domains metadata uri and lock that domain from being modified function setAndLockDomainMetadata(uint256 id, string memory uri) external; // Lock a domain's metadata so that it cannot be changed function lockDomainMetadata(uint256 id, bool toLock) external; // Update a domain's metadata uri function setDomainMetadataUri(uint256 id, string memory uri) external; // Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places) function setDomainRoyaltyAmount(uint256 id, uint256 amount) external; // Returns whether an address is a controller function isController(address account) external view returns (bool); // Checks whether or not a domain exists function domainExists(uint256 id) external view returns (bool); // Returns the original minter of a domain function minterOf(uint256 id) external view returns (address); // Checks if a domains metadata is locked function isDomainMetadataLocked(uint256 id) external view returns (bool); // Returns the address which locked the domain metadata function domainMetadataLockedBy(uint256 id) external view returns (address); // Gets the controller that registered a domain function domainController(uint256 id) external view returns (address); // Gets a domains current royalty amount function domainRoyaltyAmount(uint256 id) external view returns (uint256); // Returns the parent domain of a child domain function parentOf(uint256 id) external view returns (uint256); } // 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 StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert( _BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1) ); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import {IRegistrar} from "./IRegistrar.sol"; interface IZNSHub { function addRegistrar(uint256 rootDomainId, address registrar) external; function isController(address controller) external returns (bool); function getRegistrarForDomain(uint256 domainId) external view returns (IRegistrar); function ownerOf(uint256 domainId) external view returns (address); function domainExists(uint256 domainId) external view returns (bool); function owner() external view returns (address); function registrarBeacon() external view returns (address); function domainTransferred( address from, address to, uint256 tokenId ) external; function domainCreated( uint256 id, string calldata name, uint256 nameHash, uint256 parent, address minter, address controller, string calldata metadataUri, uint256 royaltyAmount ) external; function metadataLockChanged( uint256 id, address locker, bool isLocked ) external; function metadataChanged(uint256 id, string calldata uri) external; function royaltiesAmountChanged(uint256 id, uint256 amount) external; // Returns the parent domain of a child domain function parentOf(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.9; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap internal _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ 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.9; import "../../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.9; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.9; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @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 (last updated v4.5.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.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 ERC1967Upgrade { // 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 StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.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) { Address.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 (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(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 StorageSlot.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"); StorageSlot.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 StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.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) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // 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 IERC1822Proxiable { /** * @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) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @dev Returns the value stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed. Requirements: - `index` must be strictly less than {length}./
function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
143,907
[ 1, 1356, 326, 460, 4041, 622, 1754, 1375, 1615, 68, 316, 326, 444, 18, 531, 12, 21, 2934, 3609, 716, 1915, 854, 1158, 28790, 603, 326, 9543, 434, 924, 4832, 326, 526, 16, 471, 518, 2026, 2549, 1347, 1898, 924, 854, 3096, 578, 3723, 18, 29076, 30, 300, 1375, 1615, 68, 1297, 506, 23457, 5242, 2353, 288, 2469, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 270, 12, 694, 2502, 444, 16, 2254, 5034, 770, 13, 3238, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 565, 2583, 12, 542, 6315, 2372, 18, 2469, 405, 770, 16, 315, 3572, 25121, 694, 30, 770, 596, 434, 4972, 8863, 203, 565, 327, 444, 6315, 2372, 63, 1615, 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 ]
./full_match/4/0xaf01318163834FdeDAF9e2a4e04b9b58Aa12A984/sources/humarsContract_flat.sol
For limiting pre-sale
mapping(address => uint256) public ownedHumars;
708,183
[ 1, 1290, 1800, 310, 675, 17, 87, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 16199, 44, 379, 5913, 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 ]
pragma solidity ^0.4.24; interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } pragma solidity ^0.4.24; /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } pragma solidity ^0.4.24; library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.24; // "./PlayerBookInterface.sol"; // "./SafeMath.sol"; // "./NameFilter.sol"; // 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { /* event debug ( uint16 code, uint256 value, bytes32 msg ); */ // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, // uint256 comAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularLong is F3Devents {} contract FoMo3DWorld is modularLong, Ownable { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x789C537cE585595596D3905f401235f5A85B11d7); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D World"; string constant public symbol = "F3DW"; // uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO uint256 constant private rndGap_ = 0; // 120 seconds; // length of ICO phase. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30, 6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43, 0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56, 10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43, 8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15, 10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25, 0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20, 20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30, 10); //48% to winner, 10% to next round, 2% to com } /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _mkt = (_pot.mul(potSplit_[_winTID].marketing)) / 100; uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen).sub(_mkt); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_mkt); if (!owner.send(_com)) { _com = 0; _res = _res.add(_com); } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked((block.timestamp).add(block.difficulty).add((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add(block.gaslimit).add((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add(block.number)))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } uint256 _mkt = _eth.mul(fees_[_team].marketing) / 100; _com = _com.add(_mkt); owner.transfer(_com); _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); uint256 cut = (fees_[_team].marketing).add(13); _eth = _eth.sub(_eth.mul(cut) / 100); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) { _gen = _gen.sub(_dust); } // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, // _eventData_.comAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public onlyOwner { // make sure that its been linked. // require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } } library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 mktAmount; // amount distributed for marketing // uint256 comAmount; uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 marketing; // % of buy in thats paid for marketing } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 marketing; // % of pot thats paid to for marketing } } library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } }
* @dev prepares compression data and fires event for buy or reload tx's/ _eventData_.comAmount,
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); }
1,205,490
[ 1, 19109, 4807, 9154, 501, 471, 29564, 871, 364, 30143, 578, 7749, 2229, 1807, 19, 5411, 389, 2575, 751, 27799, 832, 6275, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 679, 4188, 12, 11890, 5034, 389, 84, 734, 16, 2254, 5034, 389, 10035, 16, 2254, 5034, 389, 546, 16, 2254, 5034, 389, 2452, 16, 478, 23, 40, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 13, 203, 565, 3238, 203, 565, 288, 203, 3639, 389, 2575, 751, 27799, 15385, 751, 273, 389, 2575, 751, 27799, 15385, 751, 397, 261, 3338, 380, 2130, 12648, 12648, 13, 397, 261, 67, 10035, 380, 2130, 12648, 12648, 12648, 3784, 1769, 203, 3639, 389, 2575, 751, 27799, 15385, 5103, 273, 389, 2575, 751, 27799, 15385, 5103, 397, 389, 84, 734, 397, 261, 86, 734, 67, 380, 2130, 12648, 12648, 12648, 12648, 12648, 2787, 9449, 1769, 203, 203, 3639, 3626, 478, 23, 758, 616, 87, 18, 265, 1638, 4188, 203, 3639, 261, 203, 5411, 389, 2575, 751, 27799, 15385, 751, 16, 203, 5411, 389, 2575, 751, 27799, 15385, 5103, 16, 203, 5411, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 529, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 546, 16, 203, 5411, 389, 2452, 16, 203, 5411, 389, 2575, 751, 27799, 91, 7872, 3178, 16, 203, 5411, 389, 2575, 751, 27799, 91, 7872, 461, 16, 203, 5411, 389, 2575, 751, 27799, 8949, 59, 265, 16, 203, 5411, 389, 2575, 751, 27799, 2704, 18411, 16, 203, 5411, 389, 2575, 751, 27799, 81, 8629, 6275, 16, 203, 5411, 389, 2575, 751, 27799, 4507, 6275, 16, 203, 5411, 389, 2575, 751, 27799, 13130, 6275, 16, 203, 5411, 23350, 7544, 18411, 67, 203, 3639, 11272, 203, 565, 2 ]
// contracts/GameItem.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract BonsaiBank is ERC721URIStorage { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private bonsaiIds; struct Bonsai { uint256 lastWatered; // The last time the bonsai was watered uint256 consecutiveWaterings; // The number of waterings gone without missing a watering uint256 waterBalance; // The amount of water tokens deposited uint256 lastFertilized; // The last time the bonsai was fertilized uint256 consecutiveFertilizings; // The number of fertilizings without missing a fertilize uint256 fertilizerBalance; // The amount of fertilizer tokens deposited uint256 lifeStage; // The amount of times this bonsai has been grown or wilted } Bonsai[] bonsaiBanks; // All bonsai banks, indexible by bonsai/tokenId - 1 address botanist; // The owner of the contract, has control of the protocol address waterToken; // The ERC20 token address to use for watering address fertToken; // The ERC20 token address to use for fertilizing uint256 waterAmount; // The amount of waterTokens needed for watering uint256 fertAmount; // The amount of fertTokens needed for fertilizing uint256 waterRate; // The time delay between waterings in seconds uint256 fertRate; // The time delay between fertilizing in seconds uint256 wateringsToGrow; // The number of consecutive waterings needed to grow constructor(address _botanist) ERC721("Bonsai Bank", "BNZI") { botanist = _botanist; } modifier onlyBotanist { require(msg.sender == botanist); _; } // Getter Methods function getBotanist() public view returns(address) { return botanist; } function getWaterToken() public view returns(address) { return waterToken; } function getFertToken() public view returns(address) { return fertToken; } function getWaterAmount() public view returns(uint256) { return waterAmount; } function getFertAmount() public view returns(uint256) { return fertAmount; } function getWaterRate() public view returns(uint256) { return waterRate; } function getFertRate() public view returns(uint256) { return fertRate; } function lastWatered(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].lastWatered; } function consecutiveWaterings(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].consecutiveWaterings; } function waterBalance(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].waterBalance; } function lastFertilized(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].lastFertilized; } function consecutiveFertilizings(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].consecutiveFertilizings; } function fertilizerBalance(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].fertilizerBalance; } function lifeStage(uint256 bonsaiId) external view returns (uint256){ return bonsaiBanks[bonsaiId-1].lifeStage; } function exists(uint256 bonsaiId) external view returns (bool){ return _exists(bonsaiId); } // Setter Methods function setBotanist(address _botanist) external onlyBotanist { botanist = _botanist; } function setWaterToken(address _waterToken) external onlyBotanist { waterToken = _waterToken; } function setFertToken(address _fertToken) external onlyBotanist { fertToken = _fertToken; } function setWaterAmount(uint256 _waterAmount) external onlyBotanist { waterAmount = _waterAmount; } function setFertAmount(uint256 _fertAmount) external onlyBotanist { fertAmount = _fertAmount; } function setWaterRate(uint256 _waterRate) external onlyBotanist { waterRate = _waterRate; } function setFertRate(uint256 _fertRate) external onlyBotanist { fertRate = _fertRate; } function setWateringsToGrow(uint256 _wateringsToGrow) external onlyBotanist { wateringsToGrow = _wateringsToGrow; } // Interal only setters for Bonsai Banks function setLastWatered(uint256 bonsaiId, uint256 _lastWatered) internal { bonsaiBanks[bonsaiId-1].lastWatered = _lastWatered; } function setConsecutiveWaterings(uint256 bonsaiId, uint256 _consecutiveWaterings) internal { bonsaiBanks[bonsaiId-1].consecutiveWaterings = _consecutiveWaterings; } function setWaterBalance(uint256 bonsaiId, uint256 _waterBalance) internal { bonsaiBanks[bonsaiId-1].waterBalance = _waterBalance; } function setLastFertilized(uint256 bonsaiId, uint256 _lastFertilized) internal { bonsaiBanks[bonsaiId-1].lastFertilized = _lastFertilized; } function setConsecutiveFertilizings(uint256 bonsaiId, uint256 _consecutiveFertilizings) internal { bonsaiBanks[bonsaiId-1].consecutiveFertilizings = _consecutiveFertilizings; } function setFertilizerBalance(uint256 bonsaiId, uint256 _fertilizerBalance) internal { bonsaiBanks[bonsaiId-1].fertilizerBalance = _fertilizerBalance; } function setLifeStage(uint256 bonsaiId, uint256 _lifeStage) external { bonsaiBanks[bonsaiId-1].lifeStage = _lifeStage; } // Events event BonsaiCreated(address caretaker,uint256 _bonsaiId,string bonsaiURI,address botanist ); event BonsaiWatered(address waterer,uint256 _bonsaiId,uint256 lastWatered,uint256 consecutiveWaterings,uint256 waterBalance ); event BonsaiFertilized(address waterer,uint256 _bonsaiId,uint256 lastFertilized,uint256 consecutiveFertilizings,uint256 fertilizerBalance ); event BonsaiGrow(address botanist,uint256 _bonsaiID,string _bonsaiURI,uint256 lifeStage,uint256 consecutiveWaterings); event BonsaiWilt(address botanist,uint256 _bonsaiID,string _bonsaiURI,uint256 consecutiveFertilizings,uint256 consecutiveWaterings); event BonsaiDestroy(address botanist,uint256 _bonsaiID,uint256 waterBalance, uint256 fertilizerBalance); // Core Bonsai Bank Functionality // @dev Mints a new Bonsai Bank directly to the caretaker function mint(address caretaker, string memory bonsaiURI) external onlyBotanist returns (uint256 bonsaiId) { bonsaiIds.increment(); uint256 _bonsaiId = bonsaiIds.current(); Bonsai memory bb = Bonsai(0,0,0,0,0,0,0); _mint(caretaker, _bonsaiId); _setTokenURI(_bonsaiId, bonsaiURI); bonsaiBanks.push(bb); emit BonsaiCreated(caretaker, _bonsaiId, bonsaiURI, botanist); return _bonsaiId; } function water(uint256 _bonsaiId) external { require(bonsaiBanks[_bonsaiId - 1].lastWatered < block.timestamp - waterRate, "!waterable"); require(IERC20(waterToken).transferFrom(msg.sender, address(this), getWaterAmount()), "!watered"); bonsaiBanks[_bonsaiId - 1].lastWatered = block.timestamp; bonsaiBanks[_bonsaiId - 1].consecutiveWaterings += 1; bonsaiBanks[_bonsaiId - 1].waterBalance += getWaterAmount(); emit BonsaiWatered(msg.sender, _bonsaiId, bonsaiBanks[_bonsaiId - 1].lastWatered, bonsaiBanks[_bonsaiId - 1].consecutiveWaterings, bonsaiBanks[_bonsaiId - 1].waterBalance); } function fertilize(uint256 _bonsaiId) external { require(bonsaiBanks[_bonsaiId - 1].lastFertilized < block.timestamp - fertRate, "!fertalizable"); require(IERC20(fertToken).transferFrom(msg.sender, address(this), getFertAmount()), "!fertilized"); bonsaiBanks[_bonsaiId - 1].lastFertilized = block.timestamp; bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings += 1; bonsaiBanks[_bonsaiId - 1].fertilizerBalance += getFertAmount(); emit BonsaiFertilized(msg.sender, _bonsaiId, bonsaiBanks[_bonsaiId - 1].lastFertilized, bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings, bonsaiBanks[_bonsaiId - 1].fertilizerBalance); } function grow(uint256 _bonsaiId, string memory _bonsaiURI) external onlyBotanist { require(bonsaiBanks[_bonsaiId - 1].consecutiveWaterings >= wateringsToGrow, "!growable"); _setTokenURI(_bonsaiId, _bonsaiURI); bonsaiBanks[_bonsaiId - 1].lifeStage += 1; bonsaiBanks[_bonsaiId - 1].consecutiveWaterings = 0; emit BonsaiGrow(botanist, _bonsaiId, _bonsaiURI, bonsaiBanks[_bonsaiId - 1].lifeStage, bonsaiBanks[_bonsaiId - 1].consecutiveWaterings); } function wilt(uint256 _bonsaiId, string memory _bonsaiURI) external onlyBotanist { require(bonsaiBanks[_bonsaiId - 1].lastWatered <= block.timestamp - waterRate.mul(2), "!wiltable"); uint256 waterSlashAmount = bonsaiBanks[_bonsaiId - 1].waterBalance.mul(95).div(100); // TODO: Safe Math uint256 fertSlashAmount = bonsaiBanks[_bonsaiId - 1].fertilizerBalance.mul(95).div(100); // TODO: Safe Math require(IERC20(waterToken).transfer(botanist, waterSlashAmount), "!slashedWater"); require(IERC20(fertToken).transfer(botanist, fertSlashAmount), "!slashedFert"); _setTokenURI(_bonsaiId, _bonsaiURI); bonsaiBanks[_bonsaiId - 1].consecutiveWaterings = 0; bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings = 0; emit BonsaiWilt(botanist, _bonsaiId, _bonsaiURI, bonsaiBanks[_bonsaiId - 1].consecutiveFertilizings, bonsaiBanks[_bonsaiId - 1].consecutiveWaterings); } function destroy(uint256 _bonsaiId) external { require(ownerOf(_bonsaiId) == msg.sender, "!caretaker"); require(IERC20(waterToken).transfer(msg.sender, bonsaiBanks[_bonsaiId - 1].waterBalance), "!withdrawWater"); require(IERC20(fertToken).transfer(msg.sender, bonsaiBanks[_bonsaiId - 1].fertilizerBalance), "!withdrawFertlizer"); bonsaiBanks[_bonsaiId - 1].waterBalance = 0; bonsaiBanks[_bonsaiId - 1].fertilizerBalance = 0; _burn(_bonsaiId); emit BonsaiDestroy(botanist, _bonsaiId, bonsaiBanks[_bonsaiId - 1].waterBalance, bonsaiBanks[_bonsaiId - 1].fertilizerBalance); } }
The number of waterings gone without missing a watering
uint256 consecutiveWaterings;
12,926,546
[ 1, 1986, 1300, 434, 16313, 899, 22296, 2887, 3315, 279, 16313, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 2254, 5034, 18221, 24064, 899, 31, 4202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } 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); } library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } 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; } } 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; } } 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 IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } contract 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; } } contract DInterest is ReentrancyGuard, Ownable { using SafeMath for uint256; using DecMath for uint256; using SafeERC20 for ERC20; using Address for address; // Constants uint256 internal constant PRECISION = 10**18; uint256 internal constant ONE = 10**18; // User deposit data // Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1 struct Deposit { uint256 amount; // Amount of stablecoin deposited uint256 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds uint256 interestOwed; // Deficit incurred to the pool at time of deposit uint256 initialMoneyMarketIncomeIndex; // Money market's income index at time of deposit bool active; // True if not yet withdrawn, false if withdrawn bool finalSurplusIsNegative; uint256 finalSurplusAmount; // Surplus remaining after withdrawal uint256 mintMPHAmount; // Amount of MPH minted to user } Deposit[] internal deposits; uint256 public latestFundedDepositID; // the ID of the most recently created deposit that was funded uint256 public unfundedUserDepositAmount; // the deposited stablecoin amount whose deficit hasn't been funded // Funding data // Each funding has an ID used in the fundingNFT, which is equal to its index in `fundingList` plus 1 struct Funding { // deposits with fromDepositID < ID <= toDepositID are funded uint256 fromDepositID; uint256 toDepositID; uint256 recordedFundedDepositAmount; uint256 recordedMoneyMarketIncomeIndex; } Funding[] internal fundingList; // Params uint256 public MinDepositPeriod; // Minimum deposit period, in seconds uint256 public MaxDepositPeriod; // Maximum deposit period, in seconds uint256 public MinDepositAmount; // Minimum deposit amount for each deposit, in stablecoins uint256 public MaxDepositAmount; // Maximum deposit amount for each deposit, in stablecoins // Instance variables uint256 public totalDeposit; uint256 public totalInterestOwed; // External smart contracts IMoneyMarket public moneyMarket; ERC20 public stablecoin; IFeeModel public feeModel; IInterestModel public interestModel; IInterestOracle public interestOracle; NFT public depositNFT; NFT public fundingNFT; MPHMinter public mphMinter; // Events event EDeposit( address indexed sender, uint256 indexed depositID, uint256 amount, uint256 maturationTimestamp, uint256 interestAmount, uint256 mintMPHAmount ); event EWithdraw( address indexed sender, uint256 indexed depositID, uint256 indexed fundingID, bool early, uint256 takeBackMPHAmount ); event EFund( address indexed sender, uint256 indexed fundingID, uint256 deficitAmount, uint256 mintMPHAmount ); event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); event ESetParamUint( address indexed sender, string indexed paramName, uint256 newValue ); struct DepositLimit { uint256 MinDepositPeriod; uint256 MaxDepositPeriod; uint256 MinDepositAmount; uint256 MaxDepositAmount; } constructor( DepositLimit memory _depositLimit, address _moneyMarket, // Address of IMoneyMarket that's used for generating interest (owner must be set to this DInterest contract) address _stablecoin, // Address of the stablecoin used to store funds address _feeModel, // Address of the FeeModel contract that determines how fees are charged address _interestModel, // Address of the InterestModel contract that determines how much interest to offer address _interestOracle, // Address of the InterestOracle contract that provides the average interest rate address _depositNFT, // Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract) address _fundingNFT, // Address of the NFT representing ownership of fundings (owner must be set to this DInterest contract) address _mphMinter // Address of the contract for handling minting MPH to users ) public { // Verify input addresses require( _moneyMarket.isContract() && _stablecoin.isContract() && _feeModel.isContract() && _interestModel.isContract() && _interestOracle.isContract() && _depositNFT.isContract() && _fundingNFT.isContract() && _mphMinter.isContract(), "DInterest: An input address is not a contract" ); moneyMarket = IMoneyMarket(_moneyMarket); stablecoin = ERC20(_stablecoin); feeModel = IFeeModel(_feeModel); interestModel = IInterestModel(_interestModel); interestOracle = IInterestOracle(_interestOracle); depositNFT = NFT(_depositNFT); fundingNFT = NFT(_fundingNFT); mphMinter = MPHMinter(_mphMinter); // Ensure moneyMarket uses the same stablecoin require( moneyMarket.stablecoin() == _stablecoin, "DInterest: moneyMarket.stablecoin() != _stablecoin" ); // Ensure interestOracle uses the same moneyMarket require( interestOracle.moneyMarket() == _moneyMarket, "DInterest: interestOracle.moneyMarket() != _moneyMarket" ); // Verify input uint256 parameters require( _depositLimit.MaxDepositPeriod > 0 && _depositLimit.MaxDepositAmount > 0, "DInterest: An input uint256 is 0" ); require( _depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod, "DInterest: Invalid DepositPeriod range" ); require( _depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount, "DInterest: Invalid DepositAmount range" ); MinDepositPeriod = _depositLimit.MinDepositPeriod; MaxDepositPeriod = _depositLimit.MaxDepositPeriod; MinDepositAmount = _depositLimit.MinDepositAmount; MaxDepositAmount = _depositLimit.MaxDepositAmount; totalDeposit = 0; } /** Public actions */ function deposit(uint256 amount, uint256 maturationTimestamp) external nonReentrant { _deposit(amount, maturationTimestamp); } function withdraw(uint256 depositID, uint256 fundingID) external nonReentrant { _withdraw(depositID, fundingID, false); } function earlyWithdraw(uint256 depositID, uint256 fundingID) external nonReentrant { _withdraw(depositID, fundingID, true); } function multiDeposit( uint256[] calldata amountList, uint256[] calldata maturationTimestampList ) external nonReentrant { require( amountList.length == maturationTimestampList.length, "DInterest: List lengths unequal" ); for (uint256 i = 0; i < amountList.length; i = i.add(1)) { _deposit(amountList[i], maturationTimestampList[i]); } } function multiWithdraw( uint256[] calldata depositIDList, uint256[] calldata fundingIDList ) external nonReentrant { require( depositIDList.length == fundingIDList.length, "DInterest: List lengths unequal" ); for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) { _withdraw(depositIDList[i], fundingIDList[i], false); } } function multiEarlyWithdraw( uint256[] calldata depositIDList, uint256[] calldata fundingIDList ) external nonReentrant { require( depositIDList.length == fundingIDList.length, "DInterest: List lengths unequal" ); for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) { _withdraw(depositIDList[i], fundingIDList[i], true); } } /** Deficit funding */ function fundAll() external nonReentrant { // Calculate current deficit (bool isNegative, uint256 deficit) = surplus(); require(isNegative, "DInterest: No deficit available"); require( !depositIsFunded(deposits.length), "DInterest: All deposits funded" ); // Create funding struct uint256 incomeIndex = moneyMarket.incomeIndex(); require(incomeIndex > 0, "DInterest: incomeIndex == 0"); fundingList.push( Funding({ fromDepositID: latestFundedDepositID, toDepositID: deposits.length, recordedFundedDepositAmount: unfundedUserDepositAmount, recordedMoneyMarketIncomeIndex: incomeIndex }) ); // Update relevant values latestFundedDepositID = deposits.length; unfundedUserDepositAmount = 0; _fund(deficit); } function fundMultiple(uint256 toDepositID) external nonReentrant { require( toDepositID > latestFundedDepositID, "DInterest: Deposits already funded" ); require( toDepositID <= deposits.length, "DInterest: Invalid toDepositID" ); (bool isNegative, uint256 surplus) = surplus(); require(isNegative, "DInterest: No deficit available"); uint256 totalDeficit = 0; uint256 totalSurplus = 0; uint256 totalDepositToFund = 0; // Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded for ( uint256 id = latestFundedDepositID.add(1); id <= toDepositID; id = id.add(1) ) { Deposit storage depositEntry = _getDeposit(id); if (depositEntry.active) { // Deposit still active, use current surplus (isNegative, surplus) = surplusOfDeposit(id); } else { // Deposit has been withdrawn, use recorded final surplus (isNegative, surplus) = ( depositEntry.finalSurplusIsNegative, depositEntry.finalSurplusAmount ); } if (isNegative) { // Add on deficit to total totalDeficit = totalDeficit.add(surplus); } else { // Has surplus totalSurplus = totalSurplus.add(surplus); } if (depositEntry.active) { totalDepositToFund = totalDepositToFund.add( depositEntry.amount ); } } if (totalSurplus >= totalDeficit) { // Deposits selected have a surplus as a whole, revert revert("DInterest: Selected deposits in surplus"); } else { // Deduct surplus from totalDeficit totalDeficit = totalDeficit.sub(totalSurplus); } // Create funding struct uint256 incomeIndex = moneyMarket.incomeIndex(); require(incomeIndex > 0, "DInterest: incomeIndex == 0"); fundingList.push( Funding({ fromDepositID: latestFundedDepositID, toDepositID: toDepositID, recordedFundedDepositAmount: totalDepositToFund, recordedMoneyMarketIncomeIndex: incomeIndex }) ); // Update relevant values latestFundedDepositID = toDepositID; unfundedUserDepositAmount = unfundedUserDepositAmount.sub( totalDepositToFund ); _fund(totalDeficit); } /** Public getters */ function calculateInterestAmount( uint256 depositAmount, uint256 depositPeriodInSeconds ) public returns (uint256 interestAmount) { (, uint256 moneyMarketInterestRatePerSecond) = interestOracle .updateAndQuery(); (bool surplusIsNegative, uint256 surplusAmount) = surplus(); return interestModel.calculateInterestAmount( depositAmount, depositPeriodInSeconds, moneyMarketInterestRatePerSecond, surplusIsNegative, surplusAmount ); } function surplus() public returns (bool isNegative, uint256 surplusAmount) { uint256 totalValue = moneyMarket.totalValue(); uint256 totalOwed = totalDeposit.add(totalInterestOwed); if (totalValue >= totalOwed) { // Locked value more than owed deposits, positive surplus isNegative = false; surplusAmount = totalValue.sub(totalOwed); } else { // Locked value less than owed deposits, negative surplus isNegative = true; surplusAmount = totalOwed.sub(totalValue); } } function surplusOfDeposit(uint256 depositID) public returns (bool isNegative, uint256 surplusAmount) { Deposit storage depositEntry = _getDeposit(depositID); uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex(); uint256 currentDepositValue = depositEntry .amount .mul(currentMoneyMarketIncomeIndex) .div(depositEntry.initialMoneyMarketIncomeIndex); uint256 owed = depositEntry.amount.add(depositEntry.interestOwed); if (currentDepositValue >= owed) { // Locked value more than owed deposits, positive surplus isNegative = false; surplusAmount = currentDepositValue.sub(owed); } else { // Locked value less than owed deposits, negative surplus isNegative = true; surplusAmount = owed.sub(currentDepositValue); } } function depositIsFunded(uint256 id) public view returns (bool) { return (id <= latestFundedDepositID); } function depositsLength() external view returns (uint256) { return deposits.length; } function fundingListLength() external view returns (uint256) { return fundingList.length; } function getDeposit(uint256 depositID) external view returns (Deposit memory) { return deposits[depositID.sub(1)]; } function getFunding(uint256 fundingID) external view returns (Funding memory) { return fundingList[fundingID.sub(1)]; } function moneyMarketIncomeIndex() external returns (uint256) { return moneyMarket.incomeIndex(); } /** Param setters */ function setFeeModel(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); feeModel = IFeeModel(newValue); emit ESetParamAddress(msg.sender, "feeModel", newValue); } function setInterestModel(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); interestModel = IInterestModel(newValue); emit ESetParamAddress(msg.sender, "interestModel", newValue); } function setInterestOracle(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); interestOracle = IInterestOracle(newValue); emit ESetParamAddress(msg.sender, "interestOracle", newValue); } function setRewards(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); moneyMarket.setRewards(newValue); emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue); } function setMinDepositPeriod(uint256 newValue) external onlyOwner { require(newValue <= MaxDepositPeriod, "DInterest: invalid value"); MinDepositPeriod = newValue; emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue); } function setMaxDepositPeriod(uint256 newValue) external onlyOwner { require( newValue >= MinDepositPeriod && newValue > 0, "DInterest: invalid value" ); MaxDepositPeriod = newValue; emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue); } function setMinDepositAmount(uint256 newValue) external onlyOwner { require(newValue <= MaxDepositAmount, "DInterest: invalid value"); MinDepositAmount = newValue; emit ESetParamUint(msg.sender, "MinDepositAmount", newValue); } function setMaxDepositAmount(uint256 newValue) external onlyOwner { require( newValue >= MinDepositAmount && newValue > 0, "DInterest: invalid value" ); MaxDepositAmount = newValue; emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue); } function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI) external onlyOwner { depositNFT.setTokenURI(tokenId, newURI); } function setDepositNFTBaseURI(string calldata newURI) external onlyOwner { depositNFT.setBaseURI(newURI); } function setDepositNFTContractURI(string calldata newURI) external onlyOwner { depositNFT.setContractURI(newURI); } function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI) external onlyOwner { fundingNFT.setTokenURI(tokenId, newURI); } function setFundingNFTBaseURI(string calldata newURI) external onlyOwner { fundingNFT.setBaseURI(newURI); } function setFundingNFTContractURI(string calldata newURI) external onlyOwner { fundingNFT.setContractURI(newURI); } /** Internal getters */ function _getDeposit(uint256 depositID) internal view returns (Deposit storage) { return deposits[depositID.sub(1)]; } function _getFunding(uint256 fundingID) internal view returns (Funding storage) { return fundingList[fundingID.sub(1)]; } /** Internals */ function _deposit(uint256 amount, uint256 maturationTimestamp) internal { // Cannot deposit 0 require(amount > 0, "DInterest: Deposit amount is 0"); // Ensure deposit amount is not more than maximum require( amount >= MinDepositAmount && amount <= MaxDepositAmount, "DInterest: Deposit amount out of range" ); // Ensure deposit period is at least MinDepositPeriod uint256 depositPeriod = maturationTimestamp.sub(now); require( depositPeriod >= MinDepositPeriod && depositPeriod <= MaxDepositPeriod, "DInterest: Deposit period out of range" ); // Update totalDeposit totalDeposit = totalDeposit.add(amount); // Update funding related data uint256 id = deposits.length.add(1); unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount); // Calculate interest uint256 interestAmount = calculateInterestAmount(amount, depositPeriod); require(interestAmount > 0, "DInterest: interestAmount == 0"); // Update totalInterestOwed totalInterestOwed = totalInterestOwed.add(interestAmount); // Mint MPH for msg.sender uint256 mintMPHAmount = mphMinter.mintDepositorReward( msg.sender, interestAmount ); // Record deposit data for `msg.sender` deposits.push( Deposit({ amount: amount, maturationTimestamp: maturationTimestamp, interestOwed: interestAmount, initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(), active: true, finalSurplusIsNegative: false, finalSurplusAmount: 0, mintMPHAmount: mintMPHAmount }) ); // Transfer `amount` stablecoin to DInterest stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Lend `amount` stablecoin to money market stablecoin.safeIncreaseAllowance(address(moneyMarket), amount); moneyMarket.deposit(amount); // Mint depositNFT depositNFT.mint(msg.sender, id); // Emit event emit EDeposit( msg.sender, id, amount, maturationTimestamp, interestAmount, mintMPHAmount ); } function _withdraw( uint256 depositID, uint256 fundingID, bool early ) internal { Deposit storage depositEntry = _getDeposit(depositID); // Verify deposit is active and set to inactive require(depositEntry.active, "DInterest: Deposit not active"); depositEntry.active = false; if (early) { // Verify `now < depositEntry.maturationTimestamp` require( now < depositEntry.maturationTimestamp, "DInterest: Deposit mature, use withdraw() instead" ); } else { // Verify `now >= depositEntry.maturationTimestamp` require( now >= depositEntry.maturationTimestamp, "DInterest: Deposit not mature" ); } // Verify msg.sender owns the depositNFT require( depositNFT.ownerOf(depositID) == msg.sender, "DInterest: Sender doesn't own depositNFT" ); // Take back MPH uint256 takeBackMPHAmount = mphMinter.takeBackDepositorReward( msg.sender, depositEntry.mintMPHAmount, early ); // Update totalDeposit totalDeposit = totalDeposit.sub(depositEntry.amount); // Update totalInterestOwed totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed); // Burn depositNFT depositNFT.burn(depositID); uint256 feeAmount; uint256 withdrawAmount; if (early) { // Withdraw the principal of the deposit from money market withdrawAmount = depositEntry.amount; } else { // Withdraw the principal & the interest from money market feeAmount = feeModel.getFee(depositEntry.interestOwed); withdrawAmount = depositEntry.amount.add(depositEntry.interestOwed); } withdrawAmount = moneyMarket.withdraw(withdrawAmount); (bool depositIsNegative, uint256 depositSurplus) = surplusOfDeposit( depositID ); // If deposit was funded, payout interest to funder if (depositIsFunded(depositID)) { Funding storage f = _getFunding(fundingID); require( depositID > f.fromDepositID && depositID <= f.toDepositID, "DInterest: Deposit not funded by fundingID" ); uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex(); require( currentMoneyMarketIncomeIndex > 0, "DInterest: currentMoneyMarketIncomeIndex == 0" ); uint256 interestAmount = f .recordedFundedDepositAmount .mul(currentMoneyMarketIncomeIndex) .div(f.recordedMoneyMarketIncomeIndex) .sub(f.recordedFundedDepositAmount); // Update funding values f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub( depositEntry.amount ); f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex; // Send interest to funder uint256 transferToFunderAmount = (early && depositIsNegative) ? interestAmount.add(depositSurplus) : interestAmount; if (transferToFunderAmount > 0) { transferToFunderAmount = moneyMarket.withdraw( transferToFunderAmount ); stablecoin.safeTransfer( fundingNFT.ownerOf(fundingID), transferToFunderAmount ); } } else { // Remove deposit from future deficit fundings unfundedUserDepositAmount = unfundedUserDepositAmount.sub( depositEntry.amount ); // Record remaining surplus depositEntry.finalSurplusIsNegative = depositIsNegative; depositEntry.finalSurplusAmount = depositSurplus; } // Send `withdrawAmount - feeAmount` stablecoin to `msg.sender` stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount)); // Send `feeAmount` stablecoin to feeModel beneficiary stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount); // Emit event emit EWithdraw( msg.sender, depositID, fundingID, early, takeBackMPHAmount ); } function _fund(uint256 totalDeficit) internal { // Transfer `totalDeficit` stablecoins from msg.sender stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit); // Deposit `totalDeficit` stablecoins into moneyMarket stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit); moneyMarket.deposit(totalDeficit); // Mint fundingNFT fundingNFT.mint(msg.sender, fundingList.length); // Mint MPH for msg.sender uint256 mintMPHAmount = mphMinter.mintFunderReward( msg.sender, totalDeficit ); // Emit event uint256 fundingID = fundingList.length; emit EFund(msg.sender, fundingID, totalDeficit, mintMPHAmount); } } library DecMath { using SafeMath for uint256; uint256 internal constant PRECISION = 10**18; function decmul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISION); } function decdiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISION).div(b); } } contract ComptrollerMock { uint256 public constant CLAIM_AMOUNT = 10**18; ERC20Mock public comp; constructor (address _comp) public { comp = ERC20Mock(_comp); } function claimComp(address holder) external { comp.mint(holder, CLAIM_AMOUNT); } function getCompAddress() external view returns (address) { return address(comp); } } contract LendingPoolAddressesProviderMock { address internal pool; address internal core; function getLendingPool() external view returns (address) { return pool; } function setLendingPoolImpl(address _pool) external { pool = _pool; } function getLendingPoolCore() external view returns (address) { return core; } function setLendingPoolCoreImpl(address _pool) external { core = _pool; } } contract LendingPoolCoreMock { LendingPoolMock internal lendingPool; function setLendingPool(address lendingPoolAddress) public { lendingPool = LendingPoolMock(lendingPoolAddress); } function bounceTransfer(address _reserve, address _sender, uint256 _amount) external { ERC20 token = ERC20(_reserve); token.transferFrom(_sender, address(this), _amount); token.transfer(msg.sender, _amount); } // The equivalent of exchangeRateStored() for Compound cTokens function getReserveNormalizedIncome(address _reserve) external view returns (uint256) { (, , , , , , , , , , , address aTokenAddress, ) = lendingPool .getReserveData(_reserve); ATokenMock aToken = ATokenMock(aTokenAddress); return aToken.normalizedIncome(); } } contract LendingPoolMock { mapping(address => address) internal reserveAToken; LendingPoolCoreMock public core; constructor(address _core) public { core = LendingPoolCoreMock(_core); } function setReserveAToken(address _reserve, address _aTokenAddress) external { reserveAToken[_reserve] = _aTokenAddress; } function deposit(address _reserve, uint256 _amount, uint16) external { ERC20 token = ERC20(_reserve); core.bounceTransfer(_reserve, msg.sender, _amount); // Mint aTokens address aTokenAddress = reserveAToken[_reserve]; ATokenMock aToken = ATokenMock(aTokenAddress); aToken.mint(msg.sender, _amount); token.transfer(aTokenAddress, _amount); } function getReserveData(address _reserve) external view returns ( uint256, uint256, uint256, uint256, uint256 liquidityRate, uint256, uint256, uint256, uint256, uint256, uint256, address aTokenAddress, uint40 ) { aTokenAddress = reserveAToken[_reserve]; ATokenMock aToken = ATokenMock(aTokenAddress); liquidityRate = aToken.liquidityRate(); } } interface IFeeModel { function beneficiary() external view returns (address payable); function getFee(uint256 _txAmount) external pure returns (uint256 _feeAmount); } contract PercentageFeeModel is IFeeModel { using SafeMath for uint256; address payable public beneficiary; constructor(address payable _beneficiary) public { beneficiary = _beneficiary; } function getFee(uint256 _txAmount) external pure returns (uint256 _feeAmount) { _feeAmount = _txAmount.div(10); // Precision is decreased by 1 decimal place } } interface IInterestOracle { function updateAndQuery() external returns (bool updated, uint256 value); function query() external view returns (uint256 value); function moneyMarket() external view returns (address); } interface IInterestModel { function calculateInterestAmount( uint256 depositAmount, uint256 depositPeriodInSeconds, uint256 moneyMarketInterestRatePerSecond, bool surplusIsNegative, uint256 surplusAmount ) external view returns (uint256 interestAmount); } contract LinearInterestModel { using SafeMath for uint256; using DecMath for uint256; uint256 public constant PRECISION = 10**18; uint256 public IRMultiplier; constructor(uint256 _IRMultiplier) public { IRMultiplier = _IRMultiplier; } function calculateInterestAmount( uint256 depositAmount, uint256 depositPeriodInSeconds, uint256 moneyMarketInterestRatePerSecond, bool, /*surplusIsNegative*/ uint256 /*surplusAmount*/ ) external view returns (uint256 interestAmount) { // interestAmount = depositAmount * moneyMarketInterestRatePerSecond * IRMultiplier * depositPeriodInSeconds interestAmount = depositAmount .mul(PRECISION) .decmul(moneyMarketInterestRatePerSecond) .decmul(IRMultiplier) .mul(depositPeriodInSeconds) .div(PRECISION); } } interface IMoneyMarket { function deposit(uint256 amount) external; function withdraw(uint256 amountInUnderlying) external returns (uint256 actualAmountWithdrawn); function claimRewards() external; // Claims farmed tokens (e.g. COMP, CRV) and sends it to the rewards pool function totalValue() external returns (uint256); // The total value locked in the money market, in terms of the underlying stablecoin function incomeIndex() external returns (uint256); // Used for calculating the interest generated (e.g. cDai's price for the Compound market) function stablecoin() external view returns (address); function setRewards(address newValue) external; event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); } contract AaveMarket is IMoneyMarket, Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; using Address for address; uint16 internal constant REFERRALCODE = 20; // Aave referral program code ILendingPoolAddressesProvider public provider; // Used for fetching the current address of LendingPool ERC20 public stablecoin; constructor(address _provider, address _stablecoin) public { // Verify input addresses require( _provider != address(0) && _stablecoin != address(0), "AaveMarket: An input address is 0" ); require( _provider.isContract() && _stablecoin.isContract(), "AaveMarket: An input address is not a contract" ); provider = ILendingPoolAddressesProvider(_provider); stablecoin = ERC20(_stablecoin); } function deposit(uint256 amount) external onlyOwner { require(amount > 0, "AaveMarket: amount is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); address lendingPoolCore = provider.getLendingPoolCore(); // Transfer `amount` stablecoin from `msg.sender` stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Approve `amount` stablecoin to lendingPool stablecoin.safeIncreaseAllowance(lendingPoolCore, amount); // Deposit `amount` stablecoin to lendingPool lendingPool.deposit(address(stablecoin), amount, REFERRALCODE); } function withdraw(uint256 amountInUnderlying) external onlyOwner returns (uint256 actualAmountWithdrawn) { require(amountInUnderlying > 0, "AaveMarket: amountInUnderlying is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // Initialize aToken (, , , , , , , , , , , address aTokenAddress, ) = lendingPool .getReserveData(address(stablecoin)); IAToken aToken = IAToken(aTokenAddress); // Redeem `amountInUnderlying` aToken, since 1 aToken = 1 stablecoin aToken.redeem(amountInUnderlying); // Transfer `amountInUnderlying` stablecoin to `msg.sender` stablecoin.safeTransfer(msg.sender, amountInUnderlying); return amountInUnderlying; } function claimRewards() external {} function totalValue() external returns (uint256) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // Initialize aToken (, , , , , , , , , , , address aTokenAddress, ) = lendingPool .getReserveData(address(stablecoin)); IAToken aToken = IAToken(aTokenAddress); return aToken.balanceOf(address(this)); } function incomeIndex() external returns (uint256) { ILendingPoolCore lendingPoolCore = ILendingPoolCore( provider.getLendingPoolCore() ); return lendingPoolCore.getReserveNormalizedIncome(address(stablecoin)); } function setRewards(address newValue) external {} } interface IAToken { function redeem(uint256 _amount) external; function balanceOf(address owner) external view returns (uint256); } interface ILendingPool { function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external; function getReserveData(address _reserve) external view returns ( uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsStable, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp ); } interface ILendingPoolAddressesProvider { function getLendingPool() external view returns (address); function setLendingPoolImpl(address _pool) external; function getLendingPoolCore() external view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) external; function getLendingPoolDataProvider() external view returns (address); function setLendingPoolDataProviderImpl(address _provider) external; function getLendingPoolParametersProvider() external view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) external; function getTokenDistributor() external view returns (address); function setTokenDistributor(address _tokenDistributor) external; function getFeeProvider() external view returns (address); function setFeeProviderImpl(address _feeProvider) external; function getLendingPoolLiquidationManager() external view returns (address); function setLendingPoolLiquidationManager(address _manager) external; function getLendingPoolManager() external view returns (address); function setLendingPoolManager(address _lendingPoolManager) external; function getPriceOracle() external view returns (address); function setPriceOracle(address _priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address _lendingRateOracle) external; } interface ILendingPoolCore { // The equivalent of exchangeRateStored() for Compound cTokens function getReserveNormalizedIncome(address _reserve) external view returns (uint256); } contract CompoundERC20Market is IMoneyMarket, Ownable { using DecMath for uint256; using SafeERC20 for ERC20; using Address for address; uint256 internal constant ERRCODE_OK = 0; ICERC20 public cToken; IComptroller public comptroller; address public rewards; ERC20 public stablecoin; constructor( address _cToken, address _comptroller, address _rewards, address _stablecoin ) public { // Verify input addresses require( _cToken != address(0) && _comptroller != address(0) && _rewards != address(0) && _stablecoin != address(0), "CompoundERC20Market: An input address is 0" ); require( _cToken.isContract() && _comptroller.isContract() && _rewards.isContract() && _stablecoin.isContract(), "CompoundERC20Market: An input address is not a contract" ); cToken = ICERC20(_cToken); comptroller = IComptroller(_comptroller); rewards = _rewards; stablecoin = ERC20(_stablecoin); } function deposit(uint256 amount) external onlyOwner { require(amount > 0, "CompoundERC20Market: amount is 0"); // Transfer `amount` stablecoin from `msg.sender` stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Deposit `amount` stablecoin into cToken stablecoin.safeIncreaseAllowance(address(cToken), amount); require( cToken.mint(amount) == ERRCODE_OK, "CompoundERC20Market: Failed to mint cTokens" ); } function withdraw(uint256 amountInUnderlying) external onlyOwner returns (uint256 actualAmountWithdrawn) { require( amountInUnderlying > 0, "CompoundERC20Market: amountInUnderlying is 0" ); // Withdraw `amountInUnderlying` stablecoin from cToken require( cToken.redeemUnderlying(amountInUnderlying) == ERRCODE_OK, "CompoundERC20Market: Failed to redeem" ); // Transfer `amountInUnderlying` stablecoin to `msg.sender` stablecoin.safeTransfer(msg.sender, amountInUnderlying); return amountInUnderlying; } function claimRewards() external { comptroller.claimComp(address(this)); ERC20 comp = ERC20(comptroller.getCompAddress()); comp.safeTransfer(rewards, comp.balanceOf(address(this))); } function totalValue() external returns (uint256) { uint256 cTokenBalance = cToken.balanceOf(address(this)); // Amount of stablecoin units that 1 unit of cToken can be exchanged for, scaled by 10^18 uint256 cTokenPrice = cToken.exchangeRateCurrent(); return cTokenBalance.decmul(cTokenPrice); } function incomeIndex() external returns (uint256) { return cToken.exchangeRateCurrent(); } /** Param setters */ function setRewards(address newValue) external onlyOwner { require(newValue.isContract(), "CompoundERC20Market: not contract"); rewards = newValue; emit ESetParamAddress(msg.sender, "rewards", newValue); } } interface ICERC20 { function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns (uint256, uint256, uint256, uint256); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize(address liquidator, address borrower, uint256 seizeTokens) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); } interface IComptroller { function claimComp(address holder) external; function getCompAddress() external view returns (address); } contract YVaultMarket is IMoneyMarket, Ownable { using SafeMath for uint256; using DecMath for uint256; using SafeERC20 for ERC20; using Address for address; Vault public vault; ERC20 public stablecoin; constructor(address _vault, address _stablecoin) public { // Verify input addresses require( _vault != address(0) && _stablecoin != address(0), "YVaultMarket: An input address is 0" ); require( _vault.isContract() && _stablecoin.isContract(), "YVaultMarket: An input address is not a contract" ); vault = Vault(_vault); stablecoin = ERC20(_stablecoin); } function deposit(uint256 amount) external onlyOwner { require(amount > 0, "YVaultMarket: amount is 0"); // Transfer `amount` stablecoin from `msg.sender` stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Approve `amount` stablecoin to vault stablecoin.safeIncreaseAllowance(address(vault), amount); // Deposit `amount` stablecoin to vault vault.deposit(amount); } function withdraw(uint256 amountInUnderlying) external onlyOwner returns (uint256 actualAmountWithdrawn) { require( amountInUnderlying > 0, "YVaultMarket: amountInUnderlying is 0" ); // Withdraw `amountInShares` shares from vault uint256 sharePrice = vault.getPricePerFullShare(); uint256 amountInShares = amountInUnderlying.decdiv(sharePrice); vault.withdraw(amountInShares); // Transfer stablecoin to `msg.sender` actualAmountWithdrawn = stablecoin.balanceOf(address(this)); stablecoin.safeTransfer(msg.sender, actualAmountWithdrawn); } function claimRewards() external {} function totalValue() external returns (uint256) { uint256 sharePrice = vault.getPricePerFullShare(); uint256 shareBalance = vault.balanceOf(address(this)); return shareBalance.decmul(sharePrice); } function incomeIndex() external returns (uint256) { return vault.getPricePerFullShare(); } function setRewards(address newValue) external {} } interface Vault { function deposit(uint256) external; function withdraw(uint256) external; function getPricePerFullShare() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `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 IRewards { function notifyRewardAmount(uint256 reward) external; } contract MPHMinter is Ownable { using Address for address; using DecMath for uint256; using SafeMath for uint256; uint256 internal constant PRECISION = 10**18; /** @notice The multiplier applied to the interest generated by a pool when minting MPH */ mapping(address => uint256) public poolMintingMultiplier; /** @notice The multiplier applied to the interest generated by a pool when letting depositors keep MPH */ mapping(address => uint256) public poolDepositorRewardMultiplier; /** @notice The multiplier applied to the interest generated by a pool when letting deficit funders keep MPH */ mapping(address => uint256) public poolFunderRewardMultiplier; /** @notice Multiplier used for calculating dev reward */ uint256 public devRewardMultiplier; event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); event ESetParamUint( address indexed sender, string indexed paramName, uint256 newValue ); /** External contracts */ MPHToken public mph; address public govTreasury; address public devWallet; constructor( address _mph, address _govTreasury, address _devWallet, uint256 _devRewardMultiplier ) public { mph = MPHToken(_mph); govTreasury = _govTreasury; devWallet = _devWallet; devRewardMultiplier = _devRewardMultiplier; } function mintDepositorReward(address to, uint256 interestAmount) external returns (uint256) { uint256 multiplier = poolMintingMultiplier[msg.sender]; uint256 mintAmount = interestAmount.decmul(multiplier); if (mintAmount == 0) { // sender is not a pool/has been deactivated return 0; } mph.ownerMint(to, mintAmount); mph.ownerMint(devWallet, mintAmount.decmul(devRewardMultiplier)); return mintAmount; } function mintFunderReward(address to, uint256 interestAmount) external returns (uint256) { uint256 multiplier = poolMintingMultiplier[msg.sender].decmul( poolFunderRewardMultiplier[msg.sender] ); uint256 mintAmount = interestAmount.decmul(multiplier); if (mintAmount == 0) { // sender is not a pool/has been deactivated return 0; } mph.ownerMint(to, mintAmount); mph.ownerMint(devWallet, mintAmount.decmul(devRewardMultiplier)); return mintAmount; } function takeBackDepositorReward( address from, uint256 mintMPHAmount, bool early ) external returns (uint256) { uint256 takeBackAmount = early ? mintMPHAmount : mintMPHAmount.decmul( PRECISION.sub(poolDepositorRewardMultiplier[msg.sender]) ); if (takeBackAmount == 0) { // sender is not a pool/has been deactivated return 0; } mph.ownerTransfer(from, govTreasury, takeBackAmount); return takeBackAmount; } /** Param setters */ function setGovTreasury(address newValue) external onlyOwner { require(newValue != address(0), "MPHMinter: 0 address"); govTreasury = newValue; emit ESetParamAddress(msg.sender, "govTreasury", newValue); } function setDevWallet(address newValue) external onlyOwner { require(newValue != address(0), "MPHMinter: 0 address"); devWallet = newValue; emit ESetParamAddress(msg.sender, "devWallet", newValue); } function setPoolMintingMultiplier(address pool, uint256 newMultiplier) external onlyOwner { require(pool.isContract(), "MPHMinter: pool not contract"); poolMintingMultiplier[pool] = newMultiplier; emit ESetParamUint(msg.sender, "poolMintingMultiplier", newMultiplier); } function setPoolDepositorRewardMultiplier( address pool, uint256 newMultiplier ) external onlyOwner { require(pool.isContract(), "MPHMinter: pool not contract"); require(newMultiplier <= PRECISION, "MPHMinter: invalid multiplier"); poolDepositorRewardMultiplier[pool] = newMultiplier; emit ESetParamUint( msg.sender, "poolDepositorRewardMultiplier", newMultiplier ); } function setPoolFunderRewardMultiplier(address pool, uint256 newMultiplier) external onlyOwner { require(pool.isContract(), "MPHMinter: pool not contract"); poolFunderRewardMultiplier[pool] = newMultiplier; emit ESetParamUint( msg.sender, "poolFunderRewardMultiplier", newMultiplier ); } } interface OneSplitAudit { function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns (uint256 returnAmount); function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); } contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require( _msgSender() == rewardDistribution, "Caller is not reward distribution" ); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(address _stakeToken) public { stakeToken = IERC20(_stakeToken); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); } } contract Rewards is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public rewardToken; OneSplitAudit public oneSplit; uint256 public constant DURATION = 7 days; uint256 public starttime; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; bool public initialized = false; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier checkStart { require(block.timestamp >= starttime, "Rewards: not start"); _; } constructor( address _stakeToken, address _rewardToken, address _oneSplit, uint256 _starttime ) public LPTokenWrapper(_stakeToken) { rewardToken = IERC20(_rewardToken); oneSplit = OneSplitAudit(_oneSplit); starttime = _starttime; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Rewards: cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Rewards: cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { _notifyRewardAmount(reward); } function dump(address token, uint256 parts) external { require(token != address(stakeToken), "Rewards: no dump stakeToken"); require(token != address(rewardToken), "Rewards: no dump rewardToken"); // dump token for rewardToken uint256 tokenBalance = IERC20(token).balanceOf(address(this)); (uint256 returnAmount, uint256[] memory distribution) = oneSplit .getExpectedReturn( token, address(rewardToken), tokenBalance, parts, 0 ); uint256 receivedRewardTokenAmount = oneSplit.swap( token, address(rewardToken), tokenBalance, returnAmount, distribution, 0 ); // notify reward _notifyRewardAmount(receivedRewardTokenAmount); } function _notifyRewardAmount(uint256 reward) internal { // https://sips.synthetix.io/sips/sip-77 require( reward < uint256(-1) / 10**18, "Rewards: rewards too large, would lock" ); if (block.timestamp > starttime) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } } contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract NFT is ERC721Metadata, Ownable { string internal _contractURI; constructor(string memory name, string memory symbol) public ERC721Metadata(name, symbol) {} function contractURI() external view returns (string memory) { return _contractURI; } function mint(address to, uint256 tokenId) external onlyOwner { _safeMint(to, tokenId); } function burn(uint256 tokenId) external onlyOwner { _burn(tokenId); } function setContractURI(string calldata newURI) external onlyOwner { _contractURI = newURI; } function setTokenURI(uint256 tokenId, string calldata newURI) external onlyOwner { _setTokenURI(tokenId, newURI); } function setBaseURI(string calldata newURI) external onlyOwner { _setBaseURI(newURI); } } contract ATokenMock is ERC20, ERC20Detailed { using SafeMath for uint256; using DecMath for uint256; uint256 internal constant YEAR = 31556952; // Number of seconds in one Gregorian calendar year (365.2425 days) ERC20 public dai; uint256 public liquidityRate; uint256 public normalizedIncome; address[] public users; mapping(address => bool) public isUser; constructor(address _dai) public ERC20Detailed("aDAI", "aDAI", 18) { dai = ERC20(_dai); liquidityRate = 10 ** 26; // 10% APY normalizedIncome = 10 ** 27; } function redeem(uint256 _amount) external { _burn(msg.sender, _amount); dai.transfer(msg.sender, _amount); } function mint(address _user, uint256 _amount) external { _mint(_user, _amount); if (!isUser[_user]) { users.push(_user); isUser[_user] = true; } } function mintInterest(uint256 _seconds) external { uint256 interest; address user; for (uint256 i = 0; i < users.length; i++) { user = users[i]; interest = balanceOf(user).mul(_seconds).mul(liquidityRate).div(YEAR.mul(10**27)); _mint(user, interest); } normalizedIncome = normalizedIncome.mul(_seconds).mul(liquidityRate).div(YEAR.mul(10**27)).add(normalizedIncome); } function setLiquidityRate(uint256 _liquidityRate) external { liquidityRate = _liquidityRate; } } contract CERC20Mock is ERC20, ERC20Detailed { address public dai; uint256 internal _supplyRate; uint256 internal _exchangeRate; constructor(address _dai) public ERC20Detailed("cDAI", "cDAI", 8) { dai = _dai; uint256 daiDecimals = ERC20Detailed(_dai).decimals(); _exchangeRate = 2 * (10**(daiDecimals + 8)); // 1 cDAI = 0.02 DAI _supplyRate = 45290900000; // 10% supply rate per year } function mint(uint256 amount) external returns (uint256) { require( ERC20(dai).transferFrom(msg.sender, address(this), amount), "Error during transferFrom" ); // 1 DAI _mint(msg.sender, (amount * 10**18) / _exchangeRate); return 0; } function redeemUnderlying(uint256 amount) external returns (uint256) { _burn(msg.sender, (amount * 10**18) / _exchangeRate); require( ERC20(dai).transfer(msg.sender, amount), "Error during transfer" ); // 1 DAI return 0; } function exchangeRateStored() external view returns (uint256) { return _exchangeRate; } function exchangeRateCurrent() external view returns (uint256) { return _exchangeRate; } function _setExchangeRateStored(uint256 _rate) external returns (uint256) { _exchangeRate = _rate; } function supplyRatePerBlock() external view returns (uint256) { return _supplyRate; } function _setSupplyRatePerBlock(uint256 _rate) external { _supplyRate = _rate; } } contract ERC20Mock is ERC20, ERC20Detailed("", "", 6) { function mint(address to, uint256 amount) public { _mint(to, amount); } } contract VaultMock is ERC20, ERC20Detailed { using SafeMath for uint256; using DecMath for uint256; ERC20 public underlying; constructor(address _underlying) public ERC20Detailed("yUSD", "yUSD", 18) { underlying = ERC20(_underlying); } function deposit(uint256 tokenAmount) public { uint256 sharePrice = getPricePerFullShare(); _mint(msg.sender, tokenAmount.decdiv(sharePrice)); underlying.transferFrom(msg.sender, address(this), tokenAmount); } function withdraw(uint256 sharesAmount) public { uint256 sharePrice = getPricePerFullShare(); uint256 underlyingAmount = sharesAmount.decmul(sharePrice); _burn(msg.sender, sharesAmount); underlying.transfer(msg.sender, underlyingAmount); } function getPricePerFullShare() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { return 10**18; } return underlying.balanceOf(address(this)).decdiv(_totalSupply); } } contract EMAOracle is IInterestOracle { using SafeMath for uint256; using DecMath for uint256; uint256 internal constant PRECISION = 10**18; /** Immutable parameters */ uint256 public UPDATE_INTERVAL; uint256 public UPDATE_MULTIPLIER; uint256 public ONE_MINUS_UPDATE_MULTIPLIER; /** Public variables */ uint256 public emaStored; uint256 public lastIncomeIndex; uint256 public lastUpdateTimestamp; /** External contracts */ IMoneyMarket public moneyMarket; constructor( uint256 _emaInitial, uint256 _updateInterval, uint256 _smoothingFactor, uint256 _averageWindowInIntervals, address _moneyMarket ) public { emaStored = _emaInitial; UPDATE_INTERVAL = _updateInterval; lastUpdateTimestamp = now; uint256 updateMultiplier = _smoothingFactor.div(_averageWindowInIntervals.add(1)); UPDATE_MULTIPLIER = updateMultiplier; ONE_MINUS_UPDATE_MULTIPLIER = PRECISION.sub(updateMultiplier); moneyMarket = IMoneyMarket(_moneyMarket); lastIncomeIndex = moneyMarket.incomeIndex(); } function updateAndQuery() public returns (bool updated, uint256 value) { uint256 timeElapsed = now - lastUpdateTimestamp; if (timeElapsed < UPDATE_INTERVAL) { return (false, emaStored); } // save gas by loading storage variables to memory uint256 _lastIncomeIndex = lastIncomeIndex; uint256 _emaStored = emaStored; uint256 newIncomeIndex = moneyMarket.incomeIndex(); uint256 incomingValue = newIncomeIndex.sub(_lastIncomeIndex).decdiv(_lastIncomeIndex).div(timeElapsed); updated = true; value = incomingValue.mul(UPDATE_MULTIPLIER).add(_emaStored.mul(ONE_MINUS_UPDATE_MULTIPLIER)).div(PRECISION); emaStored = value; lastIncomeIndex = newIncomeIndex; lastUpdateTimestamp = now; } function query() public view returns (uint256 value) { return emaStored; } } contract MPHToken is ERC20, ERC20Detailed, Ownable { constructor() public ERC20Detailed("88mph.app", "MPH", 18) {} function ownerMint(address account, uint256 amount) public onlyOwner returns (bool) { _mint(account, amount); return true; } function ownerTransfer( address from, address to, uint256 amount ) public onlyOwner returns (bool) { _transfer(from, to, amount); return true; } }
bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7/* @dev Mapping of interface ids to whether or not it's supported./ Derived contracts need only register support for their own interfaces, we register support for ERC165 itself here
constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); }
7,369,994
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 2668, 28064, 1358, 12, 3890, 24, 2506, 3719, 422, 374, 92, 1611, 1403, 71, 29, 69, 27, 19, 225, 9408, 434, 1560, 3258, 358, 2856, 578, 486, 518, 1807, 3260, 18, 19, 14969, 2950, 20092, 1608, 1338, 1744, 2865, 364, 3675, 4953, 7349, 16, 732, 1744, 2865, 364, 4232, 39, 28275, 6174, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 2713, 288, 203, 203, 203, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 28275, 1769, 203, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: WTFPL pragma solidity 0.8.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract VotingGovernance { using SafeERC20 for IERC20; enum VoteType { Against, For, Abstain } enum ProposalStatus { Open, Cancelled, Failed, Executed } uint64 public constant MINIMUM_DELAY = 1 days; /** * @notice Token to be used for proposal voting */ address public immutable tokenAddress; /** * @notice Minimum number of votes required to pass a proposal */ uint128 public immutable quorumMin; /** * @notice Minimum number of votes required for submitting a proposal */ uint128 public immutable votesMin; mapping(bytes32 => Proposal) public proposals; event SubmitProposal(bytes32 indexed hash); event CancelProposal(bytes32 indexed hash); event ExecuteProposal(bytes32 indexed hash, address executor); event CastVote(bytes32 indexed hash, address voter, uint128 votes, VoteType indexed voteType); event WithdrawTokens(bytes32 indexed hash, address withdrawer, uint128 amount); struct Proposal { address proposer; bytes[] data; uint64 startBlock; uint64 endBlock; uint128 quorum; uint128 againstVotes; uint128 forVotes; uint128 abstainVotes; mapping(address => uint128) votes; ProposalStatus status; } constructor( address _tokenAddress, uint128 _quorumMin, uint128 _votesMin ) { tokenAddress = _tokenAddress; quorumMin = _quorumMin; votesMin = _votesMin; } function hashProposal( address proposer, bytes[] memory data, uint64 startBlock, uint64 endBlock, uint128 quorum ) public pure returns (bytes32) { return keccak256(abi.encode(proposer, keccak256(abi.encode(data)), startBlock, endBlock, quorum)); } /** * @notice Anyone can submit a proposal to add/remove committee member or change committee quorum */ function submitProposal( bytes[] memory data, uint64 startBlock, uint64 endBlock, uint128 quorum, uint128 votes, VoteType voteType ) external { require(startBlock > 0, "DAOKIT: INVALID_START_BLOCK"); require(endBlock >= block.timestamp + MINIMUM_DELAY, "DAOKIT: INVALID_END_BLOCK"); require(quorum >= quorumMin, "DAOKIT: INVALID_QUORUM"); require(votes >= votesMin, "DAOKIT: INSUFFICIENT_VOTES"); bytes32 hash = hashProposal(msg.sender, data, startBlock, endBlock, quorum); Proposal storage proposal = proposals[hash]; require(proposal.startBlock == 0, "DAOKIT: DUPLICATE_PROPOSAL"); proposal.proposer = msg.sender; proposal.data = data; proposal.startBlock = startBlock; proposal.endBlock = endBlock; proposal.quorum = quorum; emit SubmitProposal(hash); _castVote(proposal, hash, votes, voteType); } /** * @notice Anyone can cast a vote for a proposal by locking up tokens */ function castVote( bytes32 hash, uint128 votes, VoteType voteType ) external { Proposal storage proposal = proposals[hash]; require(proposal.proposer != address(0), "DAOKIT: INVALID_HASH"); require(proposal.endBlock > block.timestamp, "DAOKIT: EXPIRED"); require(proposal.status == ProposalStatus.Open, "DAOKIT: NOT_OPEN"); require(proposal.votes[msg.sender] == 0, "DAOKIT: VOTE_CASTED"); _castVote(proposal, hash, votes, voteType); } function _castVote( Proposal storage proposal, bytes32 hash, uint128 votes, VoteType voteType ) internal { IERC20(tokenAddress).safeTransferFrom(msg.sender, address(this), votes); if (voteType == VoteType.Against) { proposal.againstVotes += votes; } else if (voteType == VoteType.For) { proposal.forVotes += votes; } else { proposal.abstainVotes += votes; } proposal.votes[msg.sender] = votes; emit CastVote(hash, msg.sender, votes, voteType); } /** * @notice Proposer can cancel a submitted proposal */ function cancelProposal(bytes32 hash) external { Proposal storage proposal = proposals[hash]; require(proposal.proposer == msg.sender, "DAOKIT: INVALID_HASH"); require(proposal.endBlock > block.timestamp, "DAOKIT: EXPIRED"); require(proposal.status == ProposalStatus.Open, "DAOKIT: NOT_OPEN"); require(!_quorumReached(proposal), "DAOKIT: QUORUM_REACHED"); proposal.status = ProposalStatus.Cancelled; emit CancelProposal(hash); } /** * @notice Anyone can execute a proposal that passed its quorum and whose `forVotes` is greater than `againstVotes` */ function executeProposal(bytes32 hash) external { Proposal storage proposal = proposals[hash]; require(proposal.status == ProposalStatus.Open, "DAOKIT: INVALID_STATUS"); require(_quorumReached(proposal), "DAOKIT: QUORUM_NOT_REACHED"); require(_voteSucceeded(proposal), "DAOKIT: VOTE_FAILED"); proposal.status = ProposalStatus.Executed; for (uint256 i; i < proposal.data.length; i++) { (bool success, ) = address(this).call(proposal.data[i]); require(success, "DAOKIT: TRANSACTION_REVERTED"); } emit ExecuteProposal(hash, msg.sender); } /** * @notice Voters can withdraw their tokens they locked up if the proposal deadline has passed */ function withdrawTokens(bytes32 hash) external { Proposal storage proposal = proposals[hash]; // if the vote has ended or quorum reached but vote failed if (proposal.endBlock <= block.timestamp && (!_quorumReached(proposal) || !_voteSucceeded(proposal))) { proposal.status = ProposalStatus.Failed; } else { require(proposal.status != ProposalStatus.Open, "DAOKIT: INVALID_STATUS"); } uint128 votes = proposal.votes[msg.sender]; require(votes > 0, "DAOKIT: VOTE_NOT_CASTED"); proposal.votes[msg.sender] = 0; IERC20(tokenAddress).safeTransfer(msg.sender, votes); emit WithdrawTokens(hash, msg.sender, votes); } function _quorumReached(Proposal storage proposal) internal view returns (bool) { return proposal.quorum <= proposal.forVotes + proposal.abstainVotes; } function _voteSucceeded(Proposal storage proposal) internal view returns (bool) { return proposal.forVotes > proposal.againstVotes; } }
* @notice Anyone can execute a proposal that passed its quorum and whose `forVotes` is greater than `againstVotes`/
function executeProposal(bytes32 hash) external { Proposal storage proposal = proposals[hash]; require(proposal.status == ProposalStatus.Open, "DAOKIT: INVALID_STATUS"); require(_quorumReached(proposal), "DAOKIT: QUORUM_NOT_REACHED"); require(_voteSucceeded(proposal), "DAOKIT: VOTE_FAILED"); proposal.status = ProposalStatus.Executed; for (uint256 i; i < proposal.data.length; i++) { (bool success, ) = address(this).call(proposal.data[i]); require(success, "DAOKIT: TRANSACTION_REVERTED"); } emit ExecuteProposal(hash, msg.sender); }
6,349,295
[ 1, 2961, 476, 848, 1836, 279, 14708, 716, 2275, 2097, 31854, 471, 8272, 1375, 1884, 29637, 68, 353, 6802, 2353, 1375, 23095, 334, 29637, 68, 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, 1836, 14592, 12, 3890, 1578, 1651, 13, 3903, 288, 203, 3639, 19945, 2502, 14708, 273, 450, 22536, 63, 2816, 15533, 203, 3639, 2583, 12, 685, 8016, 18, 2327, 422, 19945, 1482, 18, 3678, 16, 315, 9793, 3141, 1285, 30, 10071, 67, 8608, 8863, 203, 3639, 2583, 24899, 372, 16105, 23646, 12, 685, 8016, 3631, 315, 9793, 3141, 1285, 30, 10110, 916, 2799, 67, 4400, 67, 29416, 15023, 8863, 203, 3639, 2583, 24899, 25911, 30500, 12, 685, 8016, 3631, 315, 9793, 3141, 1285, 30, 776, 51, 1448, 67, 11965, 8863, 203, 203, 3639, 14708, 18, 2327, 273, 19945, 1482, 18, 23839, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 14708, 18, 892, 18, 2469, 31, 277, 27245, 288, 203, 5411, 261, 6430, 2216, 16, 262, 273, 1758, 12, 2211, 2934, 1991, 12, 685, 8016, 18, 892, 63, 77, 19226, 203, 5411, 2583, 12, 4768, 16, 315, 9793, 3141, 1285, 30, 24896, 67, 862, 2204, 6404, 8863, 203, 3639, 289, 203, 203, 3639, 3626, 7903, 14592, 12, 2816, 16, 1234, 18, 15330, 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 ]
./full_match/1/0x512C8C57C97905134b12a8Ab8479b57a327AA6eC/sources/contracts/SANPASS.sol
* @notice (only owner) Sets the contract URI for contract metadata. @param _newContractURI The new contract URI./
function setContractURI( string calldata _newContractURI ) external onlyOwner { contractURI = _newContractURI; }
3,001,165
[ 1, 12, 3700, 3410, 13, 11511, 326, 6835, 3699, 364, 6835, 1982, 18, 225, 389, 2704, 8924, 3098, 1021, 394, 6835, 3699, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8924, 3098, 12, 203, 3639, 533, 745, 892, 389, 2704, 8924, 3098, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 6835, 3098, 273, 389, 2704, 8924, 3098, 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 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract SquidBar is ERC20("SquidBar", "xSQUID"){ using SafeMath for uint256; IERC20 public squid; constructor(IERC20 _squid) public { squid = _squid; } // Enter the bar. Pay some SQUIDs. Earn some shares. function enter(uint256 _amount) public { uint256 totalSquid = squid.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalSquid == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalSquid); _mint(msg.sender, what); } squid.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your SQUIDs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(squid.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); squid.transfer(msg.sender, what); } }
Leave the bar. Claim back your SQUIDs.
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(squid.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); squid.transfer(msg.sender, what); }
1,045,556
[ 1, 21300, 326, 4653, 18, 18381, 1473, 3433, 348, 53, 3060, 87, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8851, 12, 11890, 5034, 389, 14419, 13, 1071, 288, 203, 3639, 2254, 5034, 2078, 24051, 273, 2078, 3088, 1283, 5621, 203, 3639, 2254, 5034, 4121, 273, 389, 14419, 18, 16411, 12, 87, 26595, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 2934, 2892, 12, 4963, 24051, 1769, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 14419, 1769, 203, 3639, 17715, 350, 18, 13866, 12, 3576, 18, 15330, 16, 4121, 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 ]
pragma solidity ^0.4.24; /// @title ERC-173 Contract Ownership Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-173.md /// Note: the ERC-165 identifier for this interface is 0x7f5828d0 interface ERC173 /* is ERC165 */ { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Get the address of the owner /// @return The address of the owner. function owner() view external; /// @notice Set the address of the new owner of the contract /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f. interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x780e9d63. interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } contract bcmc is ERC165, ERC721 , ERC721Receiver /*ERC173, ERC721Metadata, ERC721Enumerable*/ { event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256('supportsInterface(bytes4)')); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('tokenByIndex(uint256)')); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('tokenURI(uint256)')); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('getApproved(uint256)')) ^ bytes4(keccak256('setApprovalForAll(address,bool)')) ^ bytes4(keccak256('isApprovedForAll(address,address)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256('exists(uint256)')); */ /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant bcmc_name = "BlockchainMovieClub"; string public constant bcmc_symbol = "BCMC"; event NewMovie(address owner, uint256 movieId); event MovieViewTokenRequested(address drmprovider, address buyer, string buyerkey, uint32 movieid, uint32 drmid); event MovieViewTokenGranted(address player, uint32 movieId); struct Movie { string url; string thumb; string title; string descript; uint256 price; uint32 duration; uint32 drmtype; uint32 rating; uint32 viewers; uint32 drmid; address drmprovider; } struct ViewToken { uint32 movieId; uint32 cgms; uint32 status; string drm; } struct Advert { string url; uint budget; uint duration; uint viewers; } struct Player { uint preference; uint capabilities; address crnt_movie; uint indx_advert; string publickey; } struct Sponsor { bool open; uint funding_start_time; uint funding_end_time; uint movie_start_time; uint movie; uint[] adverts; } /*** Storage ***/ mapping(address => Player) players; //mapping(address => Movie) movies; mapping(address => Advert) adverts; mapping(address => Sponsor) sponsors; Movie[] movies; /// @dev A mapping from movie IDs to the address that owns them. All movies have /// some valid owner address. mapping(uint256 => address) movieIndexToOwner; // @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 owner address to count of movies that address has viewRight. // Used internally inside balanceOf() to resolve viewRight count. mapping (address => uint256) viewRightTokenCount; /// @dev A mapping from movie IDs to an address that has been approved to view /// the movie by obtaining DRM meta data at any time. /// A zero value means no approval is outstanding. mapping (uint256 => address) public tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /// @dev A mapping from player address to ViewTokens mapping (address => mapping (uint256 => ViewToken)) public viewRightGrants; address public owner; // Values 0-10,000 map to 0%-100% uint256 public ownerCut; constructor() public { owner = msg.sender; ownerCut = 500; // 5% } modifier onlyOwner() { require(msg.sender == owner); _; } /// ERC173 event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev method to get owner. automatically provided by getter. //function owner() view external; //{ // return owner; //} function transferOwnership(address _newOwner) external { address prevOwner = owner; owner = _newOwner; emit OwnershipTransferred(prevOwner, _newOwner); } function setOwnerCut(uint256 _ownerCut) onlyOwner{ ownerCut = _ownerCut; } /// @dev An method that registers a new movie. /// @param _url A json structure locate the movie, cover, title on external network /// @param _price price of the pay per view /// @param _duration duration of the movie. function registerMovie( string _url, string _thumb, string _title, string _descript, uint256 _price, uint32 _duration, uint32 _drmtype, uint32 _drmid, address _drmprovider) public { Movie memory movie = Movie({ url:_url, thumb:_thumb, title:_title, descript:_descript, price:_price, duration:_duration, drmtype : _drmtype, rating:0, viewers:0, drmid:_drmid, drmprovider: _drmprovider}); uint256 movieId = movies.push(movie) - 1; //movies[movieId] = movie; movieIndexToOwner[movieId] = msg.sender; ownershipTokenCount[msg.sender]++; } /// @dev set drm provider for a new movie. function setDrmProvider( uint256 id, address _provider) public { require(id < movies.length && msg.sender == movieIndexToOwner[id]); movies[id].drmprovider = _provider; } /// @dev registers a player. /// @param _preference - Advertisement preferences 0-none, 0xFF- all. TODO: Each bit defines a preference such as SPORTS /// @param _capabilities - Player capabilities resolution 0x000000FF(HD, UHD), audio channels 0x0000FF00, DRM 0x00FF000000 /// @param _publickey - for obtaining DRM. Content provider uses this key to encrypt DRM information and add it with the /// viewing right. function registerPlayer( uint _preference, uint _capabilities, string _publickey) public { Player memory player = Player({preference:_preference, capabilities:_capabilities, crnt_movie:0, indx_advert:0, publickey:_publickey}); players[msg.sender] = player; } function registerAdvert(string url, uint budget, uint duration) public { Advert memory advert = Advert(url, budget, duration, 0); adverts[msg.sender] = advert; } function changePrice(uint _id, uint _price) public { movies[_id].price = _price; } function getPrice(uint _id) public constant returns (uint _price) { _price = movies[_id].price; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } /// @dev Request viewToken from content provider. /// @param movieid is moveie id set at the time of registratoin function requestViewToken(address drmprovider, address buyer, string buyerkey, uint32 movieid, uint32 drmid) internal { mapping (uint256 => ViewToken) viewTokens = viewRightGrants [buyer]; /// Create a token with drm pending ViewToken memory viewToken = ViewToken({movieId:uint32(movieid), cgms:1, status:1, drm:"pending"}); viewTokens[movieid] = viewToken; emit MovieViewTokenRequested(drmprovider, buyer, buyerkey, movieid, drmid); } /// @dev Grant viewToken for the player. /// @param id is moveie id set at the time of registratoin function grantViewToken( address buyer, uint32 id, string _drm) public { require(id <= movies.length && msg.sender == movies[id].drmprovider); mapping (uint256 => ViewToken) viewTokens = viewRightGrants [buyer]; /// Fill the view token with DRM data ViewToken memory viewToken = ViewToken({movieId:id, cgms:1, status:2, drm:_drm}); viewTokens[id] = viewToken; emit MovieViewTokenGranted(buyer, id); } /// @dev Purchase a movie. /// @param id is movie id set at the time of registratoin function purchaseMovie(uint32 id) public payable { uint256 _bidAmount = msg.value; address buyer = msg.sender; require(id < movies.length); Movie storage movie = movies[id]; Player storage player = players[buyer]; uint256 price = movie.price; require(_bidAmount >= price); address seller = movieIndexToOwner[id]; // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 fees = _computeCut(price); uint256 sellerProceeds = price - fees; seller.transfer(sellerProceeds); } uint256 bidExcess = _bidAmount - price; if(bidExcess > 0){ msg.sender.transfer(bidExcess); } // Request view right requestViewToken(movie.drmprovider, buyer, player.publickey,id, movie.drmid); } function getMovieDrm(uint256 index) public constant returns (uint32 movieid, uint32 cgms, string drm) { mapping (uint256 => ViewToken) viewTokens = viewRightGrants[msg.sender]; ViewToken storage token = viewTokens[index]; movieid = token.movieId; cgms = token.cgms; drm = token.drm; } /// @notice Returns all the relevant information about a specific movie. /// @param _id The ID of the interest. function getMovieData(uint _id) public constant returns( string _url, string _thumb, string _title, string _descript, uint256 _price, uint32 _duration, uint32 _drmtype, uint32 _drmstatus) { require(_id <= movies.length); _url = movies[_id].url; _thumb = movies[_id].thumb; _title = movies[_id].title; _descript = movies[_id].descript; _price = movies[_id].price; _duration = movies[_id].duration; _drmtype = movies[_id].drmtype; if(movies[_id].drmtype != 0) { mapping (uint256 => ViewToken) viewTokens = viewRightGrants[msg.sender]; ViewToken storage viewToken = viewTokens[_id]; _drmstatus = viewToken.status; } else { _drmstatus = 0; } } function getMovieUrl(uint _id) public constant returns(string _url){ _url = movies[_id].url; } function getNextAdvertUrl(uint _id) public constant returns (string _url) { //TODO //Player storage player = players[msg.sender]; //Sponsor storage sponsor = sponsors[_id]; // //if(sponsor.adverts.length == 0) revert(); //uint indx_advert = (player.indx_advert + 1) % sponsor.adverts.length; //address advert_address= sponsor.adverts[indx_advert]; //Advert storage advert = adverts[advert_address]; //_url = advert.url; } function setRating(uint _id, uint8 _rating) public { Movie storage movie = movies[_id]; movie.rating = (movie.rating * movie.viewers + _rating) / (movie.viewers + 1); movie.viewers += 1; } function getRating(uint _id) public constant returns (uint rating) { rating = movies[_id].rating; } /// @notice Returns the total number of movies. /// @dev Required for ERC-721 compliance. function totalMovies() public view returns (uint256) { return movies.length; } /// @dev Checks if a given address is the current owner of a movie. /// @param _claimant the address we are validating against. /// @param _tokenId movie id, only valid function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return movieIndexToOwner[_tokenId] == _claimant; } /// @notice Transfers a movie to another address. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the movie to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); // You can only send your own movie. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @dev Assigns ownership of a specific movie to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of movies is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership movieIndexToOwner[_tokenId] = _to; ownershipTokenCount[_from]--; // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @notice Returns the number of movies owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given movie. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = movieIndexToOwner[_tokenId]; require(_owner != address(0)); } /// helper functions for ERC-721 implementatoin of safeTransferFrom function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool result) { address tokenOwner = ownerOf(_tokenId); result = _spender == tokenOwner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } function isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) { if (!isContract(_to)) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(msg.sender, _to, _tokenId, _data); return (retval == ERC721_RECEIVED); } /// @dev Required for ERC-721 compliance function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /// @dev Required for ERC-721 compliance. function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { // safeTransferFrom(_from, _to, _tokenId, ""); transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, "")); } /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public { _transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public { address tokenowner = ownerOf(_tokenId); require(_to != tokenowner); require(msg.sender == tokenowner || isApprovedForAll(tokenowner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(tokenowner, _to, _tokenId); } /// @dev Required for ERC-721 compliance. function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /// @dev Required for ERC-721 compliance. function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /// @dev Required for ERC-721 compliance. function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } // ERC721Metadata function name() external view returns (string _name) { _name = bcmc_name; } /// @dev Required for ERC-721 compliance. function symbol() external view returns (string _symbol) { _symbol = bcmc_symbol; } /// @dev Required for ERC-721 compliance. function tokenURI(uint256 _tokenId) external view returns (string) { return getMovieUrl(_tokenId); } // ERC721Enumerable function totalSupply() external view returns (uint256) { return totalMovies(); } /// @dev Required for ERC-721 compliance. function tokenByIndex(uint256 _index) external view returns (uint256 resultToken) { if(_index <= movies.length) { resultToken = _index; } resultToken = 0; } /// @dev Required for ERC-721 compliance. function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { uint256 tokenCount = balanceOf(_owner); uint256 result = 0; if (tokenCount == 0) { return result; } else { uint256 resultIndex = 0; uint256 id; for (id = 0; id < movies.length; id++) { if (movieIndexToOwner[id] == _owner) { result = id; break; } } return result; } } /// ERC721TokenReceiver function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns(bytes4) { //return bytes4(keccak256("onERC721Received(address,uint256,bytes)")); return ERC721_RECEIVED; } }
@dev registers a player. @param _preference - Advertisement preferences 0-none, 0xFF- all. TODO: Each bit defines a preference such as SPORTS @param _capabilities - Player capabilities resolution 0x000000FF(HD, UHD), audio channels 0x0000FF00, DRM 0x00FF000000 @param _publickey - for obtaining DRM. Content provider uses this key to encrypt DRM information and add it with the viewing right.
function registerPlayer( uint _preference, uint _capabilities, string _publickey) public { Player memory player = Player({preference:_preference, capabilities:_capabilities, crnt_movie:0, indx_advert:0, publickey:_publickey}); players[msg.sender] = player; }
955,343
[ 1, 22559, 279, 7291, 18, 225, 389, 19141, 300, 4052, 1097, 291, 820, 12750, 374, 17, 6102, 16, 374, 6356, 17, 777, 18, 2660, 30, 8315, 2831, 11164, 279, 11555, 4123, 487, 348, 6354, 55, 225, 389, 22140, 300, 19185, 12359, 7861, 374, 92, 9449, 2246, 12, 44, 40, 16, 587, 44, 40, 3631, 7447, 5750, 374, 92, 2787, 2246, 713, 16, 463, 8717, 374, 92, 713, 2246, 9449, 225, 389, 482, 856, 300, 364, 28158, 3280, 463, 8717, 18, 3697, 2893, 4692, 333, 498, 358, 7347, 463, 8717, 1779, 471, 527, 518, 598, 326, 3639, 1476, 310, 2145, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1744, 12148, 12, 203, 377, 202, 202, 11890, 389, 19141, 16, 7010, 377, 202, 202, 11890, 389, 22140, 16, 203, 377, 202, 202, 1080, 389, 482, 856, 13, 7010, 377, 202, 202, 482, 7010, 565, 288, 203, 377, 202, 12148, 3778, 7291, 273, 19185, 12590, 19141, 30, 67, 19141, 16, 7010, 377, 6862, 1082, 202, 22140, 30, 67, 22140, 16, 7010, 377, 6862, 1082, 202, 3353, 496, 67, 8683, 13120, 30, 20, 16, 7010, 377, 6862, 1082, 202, 728, 92, 67, 361, 1097, 30, 20, 16, 203, 377, 6862, 1082, 202, 482, 856, 30, 67, 482, 856, 22938, 203, 202, 565, 18115, 63, 3576, 18, 15330, 65, 273, 7291, 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 ]
./full_match/42/0xc9684b52AF172C23428970edEe6Aef19182a4eab/sources/browser/ETH_price.sol
req.addBytes("_requestID", "007");
function Ethereum() public returns (bytes32 requestID) { Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); req.add("path", "ethereum.usd"); req.addInt("times", 100); sendChainlinkRequestTo(oracle, req, 100000000000000000); }
16,240,381
[ 1, 3658, 18, 1289, 2160, 2932, 67, 2293, 734, 3113, 315, 713, 27, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 512, 18664, 379, 1435, 1071, 1135, 261, 3890, 1578, 590, 734, 13, 288, 203, 3639, 7824, 1232, 18, 691, 3778, 1111, 273, 1361, 3893, 1232, 691, 12, 4688, 548, 16, 1758, 12, 2211, 3631, 333, 18, 2706, 5935, 18, 9663, 1769, 203, 540, 203, 3639, 1111, 18, 1289, 2932, 803, 3113, 315, 546, 822, 379, 18, 407, 72, 8863, 203, 3639, 1111, 18, 1289, 1702, 2932, 8293, 3113, 2130, 1769, 203, 3639, 1366, 3893, 1232, 691, 774, 12, 280, 16066, 16, 1111, 16, 2130, 12648, 17877, 1769, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "./Transaction.sol"; contract EcobitBlockchain { mapping (uint => address[]) transactions; mapping (string => address[]) userTransactions; mapping (string => User) users; mapping (string => Transaction) transactionids; /** User **/ struct User { string companyName; string password; string email; string contact; } uint public userCount = 0; function addUser(string companyName, string password, string email, string contact) public { if (doesUserExist(companyName)) { revert(); } users[companyName] = User(companyName, password, email, contact); userCount++; } function getUsersCount() public view returns(uint) { return userCount; } function getUserTransactions(string companyName) public view returns (address[]) { return userTransactions[companyName]; } function getUserTransactionsLength(string companyName) public view returns (uint) { return userTransactions[companyName].length; } function getUser(string companyName) public view returns(string, string, string, string) { return (users[companyName].companyName, users[companyName].password,users[companyName].email, users[companyName].contact); } function removeUser(string index) public { delete users[index]; userCount = userCount - 1; } function doesUserExist(string companyName) public view returns (bool) { if(userCount == 0) return false; return ( keccak256(users[companyName].companyName) == keccak256(companyName)); } function updateUserEmail(string companyName, string email) public { users[companyName].email = email; } function updateUserContact(string companyName, string contact) public { users[companyName].contact = contact; } function updateUserPassword(string companyName, string password) public { users[companyName].password = password; } /** Transaction **/ function getTransactions(uint batchid) public view returns (address[]) { return transactions[batchid]; } function getTransaction(string transactionId) public view returns (Transaction) { return transactionids[transactionId]; } function addTransaction( uint batchid, string transactionid, uint quantity, uint item_price, uint order_date, string fromOwner, string toOwner ) public returns (address) { Transaction transaction = new Transaction( batchid, transactionid, quantity, item_price, order_date, fromOwner, toOwner ); transactions[batchid].push(transaction); transactionids[transactionid] = transaction; // This is for getting transactions from transactionId. userTransactions[fromOwner].push(transaction); return transaction; } function addTransactionWithTransport( uint batchid, string transactionid, uint quantity, uint item_price, uint order_date, string fromOwner, string toOwner, string transporter, uint pickup_date, uint deliver_date ) public returns (address) { Transaction transaction = new Transaction( batchid, transactionid, quantity, item_price, order_date, fromOwner, toOwner ); transaction.setTransport( transporter, pickup_date, deliver_date ); transactions[batchid].push(transaction); transactionids[transactionid] = transaction; userTransactions[fromOwner].push(transaction); return transaction; } function updateTransport(string transactionId, string transporter, uint pickup_date, uint deliver_date) public { Transaction transaction = getTransaction(transactionId); transaction.setTransport( transporter, pickup_date, deliver_date ); } }
This is for getting transactions from transactionId.
transactionids[transactionid] = transaction;
13,002,085
[ 1, 2503, 353, 364, 8742, 8938, 628, 24112, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2492, 2232, 63, 7958, 350, 65, 273, 2492, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x575D99d27ffF5974d608b7089404daDc9e291aca/sources/contracts/ColiseumVested.sol
* @dev Toggle the mint on or off./
function toggleMintActive() external onlyOwner { mintActive = !mintActive; }
16,421,004
[ 1, 17986, 326, 312, 474, 603, 578, 3397, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10486, 49, 474, 3896, 1435, 3903, 1338, 5541, 288, 203, 3639, 312, 474, 3896, 273, 401, 81, 474, 3896, 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/0xB78573b132c7f10212b4714c8217fC91a2e660D9/sources/OBAYC.sol
Get value from a remaining id node
function getValue(uint256 _index) internal view returns (uint256) { if (remainingIds[_index] != 0) return remainingIds[_index]; else return _index; }
2,877,758
[ 1, 967, 460, 628, 279, 4463, 612, 756, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2366, 12, 11890, 5034, 389, 1615, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 17956, 2673, 63, 67, 1615, 65, 480, 374, 13, 327, 4463, 2673, 63, 67, 1615, 15533, 203, 3639, 469, 327, 389, 1615, 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 ]
./full_match/1/0x548a6610378e80A0cFEE1f1738b9E70176366C64/sources/browser/1_Storage.sol
0x7a3370075a54B187d7bD5DceBf0ff2B5552d4F7D
bytes32 constant public RESERVE_ID_2 = 0xffabcd0000000000000000000000000000000000000000000000000000000000;
3,088,355
[ 1, 20, 92, 27, 69, 3707, 26874, 5877, 69, 6564, 38, 2643, 27, 72, 27, 70, 40, 25, 40, 311, 38, 74, 20, 1403, 22, 38, 2539, 9401, 72, 24, 42, 27, 40, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1731, 1578, 5381, 1071, 2438, 2123, 3412, 67, 734, 67, 22, 273, 374, 5297, 378, 4315, 12648, 12648, 12648, 12648, 12648, 12648, 2787, 9449, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c181908193c1d04151311061912521f13">[email&#160;protected]</a>> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); 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 tokenId); event Approval(address indexed owner, address indexed approved, uint256 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); } contract PokemonPow is ERC721 { address cryptoVideoGames = 0xdEc14D8f4DA25108Fd0d32Bf2DeCD9538564D069; address cryptoVideoGameItems = 0xD2606C9bC5EFE092A8925e7d6Ae2F63a84c5FDEa; /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new pow comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoKotakuPokemonPow"; // solhint-disable-line string public constant SYMBOL = "PokemonPow"; // solhint-disable-line uint256 private startingPrice = 0.005 ether; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.5 ether; /*** STORAGE ***/ /// @dev A mapping from pow IDs to the address that owns them. All pows have /// some valid owner address. mapping (uint256 => address) public powIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from PowIDs to an address that has been approved to call /// transferFrom(). Each Pow can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public powIndexToApproved; // @dev A mapping from PowIDs to the price of the token. mapping (uint256 => uint256) private powIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Pow { string name; uint gameId; uint gameItemId1; uint gameItemId2; } Pow[] private pows; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function PokemonPow() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); powIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo Pow with the given name, with given _price and assignes it to an address. function createPromoPow(address _owner, string _name, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { address powOwner = _owner; if (powOwner == address(0)) { powOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createPow(_name, powOwner, _price, _gameId, _gameItemId1, _gameItemId2); } /// @dev Creates a new Pow with the given name. function createContractPow(string _name, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { _createPow(_name, address(this), startingPrice, _gameId, _gameItemId1, _gameItemId2); } /// @notice Returns all the relevant information about a specific pow. /// @param _tokenId The tokenId of the pow of interest. function getPow(uint256 _tokenId) public view returns ( uint256 Id, string powName, uint256 sellingPrice, address owner, uint gameId, uint gameItemId1, uint gameItemId2 ) { Pow storage pow = pows[_tokenId]; Id = _tokenId; powName = pow.name; sellingPrice = powIndexToPrice[_tokenId]; owner = powIndexToOwner[_tokenId]; gameId = pow.gameId; gameItemId1 = pow.gameItemId1; gameItemId2 = pow.gameItemId2; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = powIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = powIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = powIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 gameOwnerPayment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 5), 100)); uint256 gameItemOwnerPayment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 5), 100)); uint256 payment = sellingPrice - gameOwnerPayment - gameOwnerPayment - gameItemOwnerPayment - gameItemOwnerPayment; uint256 purchaseExcess = SafeMath.sub(msg.value,sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100); } else if (sellingPrice < secondStepLimit) { // second stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 180), 100); } else { // third stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); } _transfer(oldOwner, newOwner, _tokenId); TokenSold(_tokenId, sellingPrice, powIndexToPrice[_tokenId], oldOwner, newOwner, pows[_tokenId].name); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.2) } msg.sender.transfer(purchaseExcess); _transferDivs(gameOwnerPayment, gameItemOwnerPayment, _tokenId); } /// Divident distributions function _transferDivs(uint256 _gameOwnerPayment, uint256 _gameItemOwnerPayment, uint256 _tokenId) private { CryptoVideoGames gamesContract = CryptoVideoGames(cryptoVideoGames); CryptoVideoGameItem gameItemContract = CryptoVideoGameItem(cryptoVideoGameItems); address gameOwner = gamesContract.getVideoGameOwner(pows[_tokenId].gameId); address gameItem1Owner = gameItemContract.getVideoGameItemOwner(pows[_tokenId].gameItemId1); address gameItem2Owner = gameItemContract.getVideoGameItemOwner(pows[_tokenId].gameItemId2); gameOwner.transfer(_gameOwnerPayment); gameItem1Owner.transfer(_gameItemOwnerPayment); gameItem2Owner.transfer(_gameItemOwnerPayment); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return powIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = powIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose pow tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire pows array looking for pows belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPows = totalSupply(); uint256 resultIndex = 0; uint256 powId; for (powId = 0; powId <= totalPows; powId++) { if (powIndexToOwner[powId] == _owner) { result[resultIndex] = powId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return pows.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return powIndexToApproved[_tokenId] == _to; } /// For creating Pow function _createPow(string _name, address _owner, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) private { Pow memory _pow = Pow({ name: _name, gameId: _gameId, gameItemId1: _gameItemId1, gameItemId2: _gameItemId2 }); uint256 newPowId = pows.push(_pow) - 1; // It&#39;s probably never going to happen, 4 billion tokens are A LOT, but // let&#39;s just be 100% sure we never let this happen. require(newPowId == uint256(uint32(newPowId))); Birth(newPowId, _name, _owner); powIndexToPrice[newPowId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newPowId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == powIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /* This function can be used by the owner of a pow item to modify the price of its pow item. */ function modifyPowPrice(uint _powId, uint256 _newPrice) public { require(_newPrice > 0); require(powIndexToOwner[_powId] == msg.sender); powIndexToPrice[_powId] = _newPrice; } /// @dev Assigns ownership of a specific Pow to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of pow is capped to 2^32 we can&#39;t overflow this ownershipTokenCount[_to]++; //transfer ownership powIndexToOwner[_tokenId] = _to; // When creating new pows _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete powIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } 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&#39;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; } } contract CryptoVideoGames { // This function will return only the owner address of a specific Video Game function getVideoGameOwner(uint _videoGameId) public view returns(address) { } } contract CryptoVideoGameItem { function getVideoGameItemOwner(uint _videoGameItemId) public view returns(address) { } }
@dev Creates a new promo Pow with the given name, with given _price and assignes it to an address.
function createPromoPow(address _owner, string _name, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { address powOwner = _owner; if (powOwner == address(0)) { powOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createPow(_name, powOwner, _price, _gameId, _gameItemId1, _gameItemId2); }
7,695,358
[ 1, 2729, 279, 394, 3012, 83, 28509, 598, 326, 864, 508, 16, 598, 864, 389, 8694, 471, 2683, 281, 518, 358, 392, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 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, 225, 445, 752, 13224, 83, 28289, 12, 2867, 389, 8443, 16, 533, 389, 529, 16, 2254, 5034, 389, 8694, 16, 2254, 389, 13957, 548, 16, 2254, 389, 13957, 17673, 21, 16, 2254, 389, 13957, 17673, 22, 13, 1071, 1338, 3865, 51, 288, 203, 203, 565, 1758, 7602, 5541, 273, 389, 8443, 31, 203, 565, 309, 261, 23509, 5541, 422, 1758, 12, 20, 3719, 288, 203, 1377, 7602, 5541, 273, 1825, 83, 1887, 31, 203, 565, 289, 203, 203, 565, 309, 261, 67, 8694, 1648, 374, 13, 288, 203, 1377, 389, 8694, 273, 5023, 5147, 31, 203, 565, 289, 203, 203, 565, 3012, 83, 6119, 1380, 9904, 31, 203, 565, 389, 2640, 28289, 24899, 529, 16, 7602, 5541, 16, 389, 8694, 16, 389, 13957, 548, 16, 389, 13957, 17673, 21, 16, 389, 13957, 17673, 22, 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 ]
./full_match/1/0x07B0226465A50300F91c8A7930f90aEcae3D6Ed4/sources/contracts/staking/SeasonV2.sol
* @dev Calculate a user's rewards amounts and clear stake points @param userAddress - The address of the user account @return Amount of ETH entitlement @return Amount of OGN entitlement/ Unable to calculate rewards because we aren't bootstrapped Nothing to unstake, no rewards to give. Season can still be bootstrapped by Series with a new stake. Only remove points from season totals if season has not ended to preserve shares proportion calculation Within claim period
function _unstake(address userAddress) internal returns (uint256, uint256) { if (!season.bootstrapped) { require(block.timestamp < endTime, 'Season: Not bootstrapped.'); return (0, 0); } User memory user = _initMemUser(userAddress); uint256 rewardETH = 0; uint256 rewardOGN = 0; if (block.timestamp < endTime) { season.totalPoints -= user.points; if (block.timestamp < claimEndTime) { (rewardETH, rewardOGN) = _calcRewards(user.points); } } emit Unstake(userAddress); return (rewardETH, rewardOGN); }
16,523,381
[ 1, 8695, 279, 729, 1807, 283, 6397, 30980, 471, 2424, 384, 911, 3143, 225, 729, 1887, 300, 1021, 1758, 434, 326, 729, 2236, 327, 16811, 434, 512, 2455, 3281, 19025, 327, 16811, 434, 531, 8318, 3281, 19025, 19, 18640, 358, 4604, 283, 6397, 2724, 732, 11526, 1404, 7065, 1845, 13389, 358, 640, 334, 911, 16, 1158, 283, 6397, 358, 8492, 18, 3265, 2753, 848, 4859, 506, 7065, 1845, 635, 9225, 598, 279, 394, 384, 911, 18, 5098, 1206, 3143, 628, 15874, 19489, 309, 15874, 711, 486, 16926, 358, 9420, 24123, 23279, 11096, 3423, 267, 7516, 3879, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 23412, 911, 12, 2867, 729, 1887, 13, 2713, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 309, 16051, 30321, 18, 12722, 1845, 13, 288, 203, 5411, 2583, 12, 2629, 18, 5508, 411, 13859, 16, 296, 1761, 2753, 30, 2288, 7065, 1845, 1093, 1769, 203, 203, 5411, 327, 261, 20, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 2177, 3778, 729, 273, 389, 2738, 3545, 1299, 12, 1355, 1887, 1769, 203, 203, 3639, 2254, 5034, 19890, 1584, 44, 273, 374, 31, 203, 3639, 2254, 5034, 19890, 51, 8318, 273, 374, 31, 203, 203, 3639, 309, 261, 2629, 18, 5508, 411, 13859, 13, 288, 203, 5411, 15874, 18, 4963, 5636, 3947, 729, 18, 4139, 31, 203, 5411, 309, 261, 2629, 18, 5508, 411, 7516, 25255, 13, 288, 203, 7734, 261, 266, 2913, 1584, 44, 16, 19890, 51, 8318, 13, 273, 389, 12448, 17631, 14727, 12, 1355, 18, 4139, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 203, 3639, 3626, 1351, 334, 911, 12, 1355, 1887, 1769, 203, 203, 3639, 327, 261, 266, 2913, 1584, 44, 16, 19890, 51, 8318, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.7.6; import "@openzeppelin/contracts/access/Ownable.sol"; //@notice Ce contrat gère un système de vote pour une petite communauté. L'administrateur qui //@notice déploie le contrat, est en charge d'ajouter les participants, et de démarrer et terminer //@notice chaque phase du processus de vote. Les participants font des propositions et les votent. //@notice github: https://github.com/brunolune/Vote-Alyra/blob/main/vote.sol contract Voting is Ownable { struct Voter { bool isRegistered; bool hasVoted; uint votedProposalId; } struct Proposal { string description; uint voteCount; } uint private winningProposalId; uint votersCount; //pour compter le nb d'électeurs ajoutés uint votesCount; //pour compter le nb de votes Proposal[] public proposals; mapping(address => Voter) whitelist; address[] public whitelistarray; mapping (uint => uint[]) winningProposalIds; enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } WorkflowStatus voteStatus = WorkflowStatus.RegisteringVoters; event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted (address voter, uint proposalId); event VotesTallied(); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); constructor () { whitelist[msg.sender].isRegistered = true; whitelistarray.push(msg.sender); votersCount = 1; } //@notice L'administrateur du vote enregistre une liste blanche d'électeurs identifiés par leur adresse Ethereum. function A_votersRegistration(address _address) public onlyOwner { require(voteStatus==WorkflowStatus.RegisteringVoters, "Registration is over"); require(!whitelist[_address].isRegistered, "This address is already registered"); whitelist[_address].isRegistered = true; whitelistarray.push(_address); votersCount++; emit VoterRegistered(_address); } //@notice L'administrateur du vote commence la session d'enregistrement des propositions. function B_proposalsRegistrationStart() public onlyOwner{ require(voteStatus==WorkflowStatus.RegisteringVoters, "Proposals Registration already started!"); require(votersCount>2,"Please add at least 1 voter!"); emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters,WorkflowStatus.ProposalsRegistrationStarted); emit ProposalsRegistrationStarted(); voteStatus = WorkflowStatus.ProposalsRegistrationStarted; } //@notice Les électeurs inscrits sont autorisés à enregistrer leurs propositions pendant que la session d'enregistrement est active. function C_proposalRegistration(string memory _proposal) public { require(keccak256(abi.encodePacked((_proposal)))!=keccak256(abi.encodePacked((""))),"Your proposal is empty!"); require(voteStatus==WorkflowStatus.ProposalsRegistrationStarted,"Proposals registration not open!"); require(whitelist[msg.sender].isRegistered, "You can't make a proposal cause you're not registered"); proposals.push(Proposal(_proposal,0)); emit ProposalRegistered(proposals.length-1); } //@notice L'administrateur met fin à la session d'enregistrement des propositions. function D_proposalsRegistrationTermination() public onlyOwner{ require(voteStatus==WorkflowStatus.ProposalsRegistrationStarted,"Proposals registration not open!"); require(proposals.length!=0,"Please add more proposals!"); emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted,WorkflowStatus.ProposalsRegistrationEnded); voteStatus = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(); emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded,WorkflowStatus.VotingSessionStarted); } //@notice L'administrateur commence la session de vote. function E_votingTimeStart() public onlyOwner{ require(voteStatus==WorkflowStatus.ProposalsRegistrationEnded,"Proposals registration not ended!"); voteStatus = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(); } //@notice Les électeurs inscrits votent pour leurs propositions préférées. function F_vote(uint propId) public { require(voteStatus == WorkflowStatus.VotingSessionStarted,"Vote not open!"); require(whitelist[msg.sender].isRegistered, "You can't vote cause you're not registered"); require(!whitelist[msg.sender].hasVoted, "You voted already"); whitelist[msg.sender].votedProposalId = propId; whitelist[msg.sender].hasVoted = true; proposals[propId].voteCount++; votesCount++; emit Voted(msg.sender, propId); } //@notice L'administrateur du vote met fin à la session de vote. function G_votingTimeTermination() public onlyOwner{ require(voteStatus == WorkflowStatus.VotingSessionStarted,"Vote not open!"); require(votesCount>0,"Nobody has voted yet!"); voteStatus = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted,WorkflowStatus.VotingSessionEnded); emit VotingSessionEnded(); } //@notice L'administrateur du vote comptabilise les votes. function H_CountVotes() public onlyOwner { require(voteStatus == WorkflowStatus.VotingSessionEnded,"Counting votes not open!"); //@dev on prend en compte la possibilité de plusieurs propositions gagnantes //@dev dont les indexes sont stockés dans winningProposalIds if (proposals[0].voteCount >= proposals[1].voteCount) winningProposalIds[0].push(0); for (uint index = 1; index < proposals.length; index++) { if (proposals[winningProposalId].voteCount < proposals[index].voteCount) { winningProposalId = index ; winningProposalIds[winningProposalId].push(winningProposalId); } else if (proposals[winningProposalId].voteCount == proposals[index].voteCount) { winningProposalIds[winningProposalId].push(index) ; } } emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded,WorkflowStatus.VotesTallied); voteStatus = WorkflowStatus.VotesTallied; emit VotesTallied(); } //@notice Tout le monde peut vérifier les derniers détails de la proposition gagnante. function I_WinningProposalIds() public view returns(uint[] memory) { require(voteStatus == WorkflowStatus.VotesTallied,"Votes not counted yet!"); //@dev on retourne un tableau avec les indices des propositions gagnantes return winningProposalIds[winningProposalId]; } function getwhitelistarray() public view returns(address[] memory){ return whitelistarray; } //@dev retourne la phase du vote dans laquelle on se trouve function getVoteStatus() public view returns (string memory) { string[6] memory Status=[ "RegisteringVoters", "ProposalsRegistrationStarted", "ProposalsRegistrationEnded", "VotingSessionStarted", "VotingSessionEnded", "VotesTallied" ]; return Status[uint(voteStatus)]; } }
@notice Tout le monde peut vérifier les derniers détails de la proposition gagnante.@dev on retourne un tableau avec les indices des propositions gagnantes
function I_WinningProposalIds() public view returns(uint[] memory) { require(voteStatus == WorkflowStatus.VotesTallied,"Votes not counted yet!"); return winningProposalIds[winningProposalId]; }
1,020,469
[ 1, 56, 659, 884, 6921, 323, 2804, 322, 331, 132, 107, 86, 1251, 18022, 4854, 15834, 414, 302, 132, 107, 13101, 87, 443, 7125, 450, 3276, 314, 346, 82, 7974, 18, 603, 325, 6561, 73, 640, 1014, 8377, 279, 8799, 18022, 4295, 2832, 450, 12388, 314, 346, 82, 970, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 467, 67, 18049, 2093, 14592, 2673, 1435, 1071, 1476, 1135, 12, 11890, 8526, 3778, 13, 288, 203, 3639, 2583, 12, 25911, 1482, 422, 11363, 1482, 18, 29637, 56, 454, 2092, 10837, 29637, 486, 26352, 4671, 4442, 1769, 203, 3639, 327, 5657, 2093, 14592, 2673, 63, 8082, 2093, 14592, 548, 15533, 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 ]
./full_match/42220/0xAf387Ee8dd07696437FEA7f007998bA52fCeb7f1/sources/contracts/CeloBridge/Validator.sol
digest the data to transactionHash address recoveredAddress = ecrecover(inputHash, sigV[index], sigR[index], sigS[index]);
function _checkEmergencySig( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address tokenAddress, uint256 _amount ) internal view returns (bool) { bytes32 funcHash = keccak256("emergencyWithdraw"); bytes32 inputHash = keccak256( abi.encode(funcHash, tokenAddress, _amount) ); for (uint256 index = 0; index < sigV.length; index++) { if ( !_checkSignature( sigV[index], sigR[index], sigS[index], inputHash ) ) return false; } return true; } modifier validatorPrecheck( uint8[] memory _sigV, bytes32[] memory _sigR, bytes32[] memory _sigS
16,335,003
[ 1, 10171, 326, 501, 358, 2492, 2310, 1758, 24616, 1887, 273, 425, 1793, 3165, 12, 2630, 2310, 16, 3553, 58, 63, 1615, 6487, 3553, 54, 63, 1615, 6487, 3553, 55, 63, 1615, 19226, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1893, 1514, 24530, 8267, 12, 203, 3639, 2254, 28, 8526, 3778, 3553, 58, 16, 203, 3639, 1731, 1578, 8526, 3778, 3553, 54, 16, 203, 3639, 1731, 1578, 8526, 3778, 3553, 55, 16, 203, 3639, 1758, 1147, 1887, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 1326, 2310, 273, 417, 24410, 581, 5034, 2932, 351, 24530, 1190, 9446, 8863, 203, 3639, 1731, 1578, 810, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 644, 2310, 16, 1147, 1887, 16, 389, 8949, 13, 203, 3639, 11272, 203, 3639, 364, 261, 11890, 5034, 770, 273, 374, 31, 770, 411, 3553, 58, 18, 2469, 31, 770, 27245, 288, 203, 5411, 309, 261, 203, 7734, 401, 67, 1893, 5374, 12, 203, 10792, 3553, 58, 63, 1615, 6487, 203, 10792, 3553, 54, 63, 1615, 6487, 203, 10792, 3553, 55, 63, 1615, 6487, 203, 10792, 810, 2310, 203, 7734, 262, 203, 5411, 262, 327, 629, 31, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 9606, 4213, 1386, 1893, 12, 203, 3639, 2254, 28, 8526, 3778, 389, 7340, 58, 16, 203, 3639, 1731, 1578, 8526, 3778, 389, 7340, 54, 16, 203, 3639, 1731, 1578, 8526, 3778, 389, 7340, 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 ]
pragma solidity ^0.4.18; pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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 Basic contracts * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer contracts for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of contracts to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } /** * @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 Standard ERC20 contracts * * @dev Implementation of the basic standard contracts. * @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); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract PAXToken is BurnableToken, PausableToken { using SafeMath for uint; string public constant name = "Pax Token"; string public constant symbol = "PAX"; uint32 public constant decimals = 10; uint256 public constant INITIAL_SUPPLY = 999500000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. * @param _company address reserve tokens (300000000) * @param _founders_1 address reserve tokens (300000000) * @param _founders_2 address reserve tokens (50000000) * @param _isPause bool (pause === true) */ function PAXToken(address _company, address _founders_1, address _founders_2, bool _isPause) public { require(_company != address(0) && _founders_1 != address(0) && _founders_2 != address(0)); paused = _isPause; totalSupply = INITIAL_SUPPLY; balances[msg.sender] = 349500000 * (10 ** uint256(decimals)); balances[_company] = 300000000 * (10 ** uint256(decimals)); balances[_founders_1] = 300000000 * (10 ** uint256(decimals)); balances[_founders_2] = 50000000 * (10 ** uint256(decimals)); emit Transfer(0x0, msg.sender, balances[msg.sender]); emit Transfer(0x0, _company, balances[_company]); emit Transfer(0x0, _founders_1, balances[_founders_1]); emit Transfer(0x0, _founders_2, balances[_founders_2]); } /** * @dev transfer contracts for a specified address, despite the pause state * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function ownersTransfer(address _to, uint256 _value) public onlyOwner returns (bool) { return BasicToken.transfer(_to, _value); } } contract Crowdsale is Pausable { struct stageInfo { uint start; uint stop; uint duration; uint bonus; uint limit; } /** * @dev Mapping with stageId = stageInfo */ mapping (uint => stageInfo) public stages; /** * @dev Mapping with adress = with balance */ mapping(address => uint) public balances; /** * @dev Softcap */ uint public constant softcap = 2500 ether; /** * @dev xDecimals */ uint public constant decimals = 1E10; /** * @dev ICO Period Number */ uint public period = 5; /** * @dev Total number of minted tokens */ uint public hardcap; /** * @dev Cost of the token */ uint public rate; /** * @dev Number of sold tokens */ uint public totalSold = 0; /** * @dev Assembled Eth */ uint256 public sumWei; /** * @dev ICO Status */ bool public state; /** * @dev Once call flag */ bool public requireOnce = true; /** * @dev Once burning flag */ bool public isBurned; /** * @dev Reserve tokens adress for company (300000000) */ address public company; /** * @dev Reserve tokens adress for founders first (300000000) */ address public founders_1; /** * @dev Reserve tokens adress for founders second (50000000) */ address public founders_2; /** * @dev The address to which the received ether will be sent */ address public multisig; /** * @dev Tokens classes */ PAXToken public token; /** * @dev Number of coins for the typical period */ uint private constant typicalBonus = 100; /** * @dev Sending tokens */ uint private sendingTokens; /** * @dev Time left */ uint private timeLeft; /** * @dev Pause date */ uint private pauseDate; /** * @dev Paused by value flag */ bool private pausedByValue; /** * @dev Manual pause flag */ bool private manualPause; event StartICO(); event StopICO(); event BurnUnsoldTokens(); event NewWalletAddress(address _to); event Refund(address _wallet, uint _val); event DateMoved(uint value); using SafeMath for uint; modifier saleIsOn() { require(state); uint stageId = getStageId(); if (period != stageId || stageId == 5) { usersPause(); (msg.sender).transfer(msg.value); } else _; } modifier isUnderHardCap() { uint tokenBalance = token.balanceOf(this); require( tokenBalance <= hardcap && tokenBalance >= 500 ); _; } function Crowdsale(address _company, address _founders_1, address _founders_2, address _token) public { multisig = owner; rate = (uint)(1 ether).div(5000); stages[0] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 130, limit: 44500000 * decimals }); stages[1] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 115, limit: 85000000 * decimals }); stages[2] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 110, limit: 100000000 * decimals }); stages[3] = stageInfo({ start: 0, stop: 0, duration: 14 days, bonus: 105, limit: 120000000 * decimals }); hardcap = 349500000 * decimals; token = PAXToken(_token); company = _company; founders_1 = _founders_1; founders_2 = _founders_2; } /** * @dev Fallback function */ function() whenNotPaused saleIsOn external payable { require (msg.value > 0); sendTokens(msg.value, msg.sender); } /** * @dev Manual sending tokens * @param _to address where sending tokens * @param _value uint256 value tokens for sending */ function manualSendTokens(address _to, uint256 _value) public onlyOwner returns(bool) { uint tokens = _value; uint avalibleTokens = token.balanceOf(this); if (tokens < avalibleTokens) { if (tokens <= stages[3].limit) { stages[3].limit = (stages[3].limit).sub(tokens); } else if (tokens <= (stages[3].limit).add(stages[2].limit)) { stages[2].limit = (stages[2].limit).sub(tokens.sub(stages[3].limit)); stages[3].limit = 0; } else if (tokens <= (stages[3].limit).add(stages[2].limit).add(stages[1].limit)) { stages[1].limit = (stages[1].limit).sub(tokens.sub(stages[3].limit).sub(stages[2].limit)); stages[3].limit = 0; stages[2].limit = 0; } else if (tokens <= (stages[3].limit).add(stages[2].limit).add(stages[1].limit).add(stages[0].limit)) { stages[0].limit = (stages[0].limit).sub(tokens.sub(stages[3].limit).sub(stages[2].limit).sub(stages[1].limit)); stages[3].limit = 0; stages[2].limit = 0; stages[1].limit = 0; } } else { tokens = avalibleTokens; stages[3].limit = 0; stages[2].limit = 0; stages[1].limit = 0; stages[0].limit = 0; } sendingTokens = sendingTokens.add(tokens); sumWei = sumWei.add(tokens.mul(rate).div(decimals)); totalSold = totalSold.add(tokens); token.ownersTransfer(_to, tokens); return true; } /** * @dev Return Etherium all investors */ function refund() public { require(sumWei < softcap && !state); uint value = balances[msg.sender]; balances[msg.sender] = 0; emit Refund(msg.sender, value); msg.sender.transfer(value); } /** * @dev Burning all tokens on mintAddress */ function burnUnsoldTokens() onlyOwner public returns(bool) { require(!state); require(!isBurned); isBurned = true; emit BurnUnsoldTokens(); token.burn(token.balanceOf(this)); if (token.paused()) { token.unpause(); } return true; } /** * @dev Starting ICO */ function startICO() public onlyOwner returns(bool) { require(stages[0].start >= now); require(requireOnce); requireOnce = false; state = true; period = 0; emit StartICO(); token.ownersTransfer(company, (uint)(300000000).mul(decimals)); token.ownersTransfer(founders_1, (uint)(300000000).mul(decimals)); token.ownersTransfer(founders_2, (uint)(50000000).mul(decimals)); return true; } /** * @dev Turning off the ICO */ function stopICO() onlyOwner public returns(bool) { state = false; emit StopICO(); if (token.paused()) { token.unpause(); } return true; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { manualPause = true; usersPause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { uint shift = now.sub(pauseDate); dateMove(shift); period = getStageId(); pausedByValue = false; manualPause = false; super.unpause(); } /** * @dev Withdrawal Etherium from smart-contract */ function withDrawal() public onlyOwner { if(!state && sumWei >= softcap) { multisig.transfer(address(this).balance); } } /** * @dev Returns stage id */ function getStageId() public view returns(uint) { uint stageId; uint today = now; if (today < stages[0].stop) { stageId = 0; } else if (today >= stages[1].start && today < stages[1].stop ) { stageId = 1; } else if (today >= stages[2].start && today < stages[2].stop ) { stageId = 2; } else if (today >= stages[3].start && today < stages[3].stop ) { stageId = 3; } else if (today >= stages[3].stop) { stageId = 4; } else { return 5; } uint tempId = (stageId > period) ? stageId : period; return tempId; } /** * @dev Returns Limit of coins for the period and Number of coins taking * into account the bonus for the period */ function getStageData() public view returns(uint tempLimit, uint tempBonus) { uint stageId = getStageId(); tempBonus = stages[stageId].bonus; if (stageId == 0) { tempLimit = stages[0].limit; } else if (stageId == 1) { tempLimit = (stages[0].limit).add(stages[1].limit); } else if (stageId == 2) { tempLimit = (stages[0].limit).add(stages[1].limit).add(stages[2].limit); } else if (stageId == 3) { tempLimit = (stages[0].limit).add(stages[1].limit).add(stages[2].limit).add(stages[3].limit); } else { tempLimit = token.balanceOf(this); tempBonus = typicalBonus; return; } tempLimit = tempLimit.sub(totalSold); return; } /** * @dev Returns the amount for which you can redeem all tokens for the current period */ function calculateStagePrice() public view returns(uint price) { uint limit; uint bonusCoefficient; (limit, bonusCoefficient) = getStageData(); price = limit.mul(rate).mul(100).div(bonusCoefficient).div(decimals); } /** * @dev Sending tokens to the recipient, based on the amount of ether that it sent * @param _etherValue uint Amount of sent ether * @param _to address The address which you want to transfer to */ function sendTokens(uint _etherValue, address _to) internal isUnderHardCap { uint limit; uint bonusCoefficient; (limit, bonusCoefficient) = getStageData(); uint tokens = (_etherValue).mul(bonusCoefficient).mul(decimals).div(100); tokens = tokens.div(rate); bool needPause; if (tokens > limit) { needPause = true; uint stageEther = calculateStagePrice(); period++; if (period == 4) { balances[msg.sender] = balances[msg.sender].add(stageEther); sumWei = sumWei.add(stageEther); token.ownersTransfer(_to, limit); totalSold = totalSold.add(limit); _to.transfer(_etherValue.sub(stageEther)); state = false; return; } balances[msg.sender] = balances[msg.sender].add(stageEther); sumWei = sumWei.add(stageEther); token.ownersTransfer(_to, limit); totalSold = totalSold.add(limit); sendTokens(_etherValue.sub(stageEther), _to); } else { require(tokens <= token.balanceOf(this)); if (limit.sub(tokens) < 500) { needPause = true; period++; } balances[msg.sender] = balances[msg.sender].add(_etherValue); sumWei = sumWei.add(_etherValue); token.ownersTransfer(_to, tokens); totalSold = totalSold.add(tokens); } if (needPause) { pausedByValue = true; usersPause(); } } /** * @dev called by the contract to pause, triggers stopped state */ function usersPause() private { pauseDate = now; paused = true; emit Pause(); } /** * @dev Moving date after the pause * @param _shift uint Time in seconds */ function dateMove(uint _shift) private returns(bool) { require(_shift > 0); uint i; if (pausedByValue) { stages[period].start = now; stages[period].stop = (stages[period].start).add(stages[period].duration); for (i = period + 1; i < 4; i++) { stages[i].start = stages[i - 1].stop; stages[i].stop = (stages[i].start).add(stages[i].duration); } } else { if (manualPause) stages[period].stop = (stages[period].stop).add(_shift); for (i = period + 1; i < 4; i++) { stages[i].start = (stages[i].start).add(_shift); stages[i].stop = (stages[i].stop).add(_shift); } } emit DateMoved(_shift); return true; } /** * @dev Returns the total number of tokens available for sale */ function tokensAmount() public view returns(uint) { return token.balanceOf(this); } /** * @dev Returns number of supplied tokens */ function tokensSupply() public view returns(uint) { return token.totalSupply(); } /** * @dev Set start date * @param _start uint Time start */ function setStartDate(uint _start) public onlyOwner returns(bool) { require(_start > now); require(requireOnce); stages[0].start = _start; stages[0].stop = _start.add(stages[0].duration); stages[1].start = stages[0].stop; stages[1].stop = stages[1].start.add(stages[1].duration); stages[2].start = stages[1].stop; stages[2].stop = stages[2].start.add(stages[2].duration); stages[3].start = stages[2].stop; stages[3].stop = stages[3].start.add(stages[3].duration); return true; } /** * @dev Sets new multisig address to which the received ether will be sent * @param _to address */ function setMultisig(address _to) public onlyOwner returns(bool) { require(_to != address(0)); multisig = _to; emit NewWalletAddress(_to); return true; } /** * @dev Change first adress with reserve(300000000 tokens) * @param _company address */ function setReserveForCompany(address _company) public onlyOwner { require(_company != address(0)); require(requireOnce); company = _company; } /** * @dev Change second adress with reserve(300000000 tokens) * @param _founders_1 address */ function setReserveForFoundersFirst(address _founders_1) public onlyOwner { require(_founders_1 != address(0)); require(requireOnce); founders_1 = _founders_1; } /** * @dev Change third adress with reserve(50000000 tokens) * @param _founders_2 address */ function setReserveForFoundersSecond(address _founders_2) public onlyOwner { require(_founders_2 != address(0)); require(requireOnce); founders_2 = _founders_2; } }
* @dev Assembled Eth/
uint256 public sumWei;
13,057,145
[ 1, 1463, 5747, 1259, 512, 451, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2142, 3218, 77, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xF39d18583fdFD746543aE22eC8D33432730431d7/sources/tests/Fingers/Fingers.sol
uint a = 0;uint b = 9999; défini la fourchette pour le choix aléatoire parmis les x possiblités de Dna ex saison 1 : rand(a=0, b=9999);
contract Fingers /*is ERC721*/ { event NewFinger(uint256 tokenId); event FingerChange(uint256 tokenId); event FingerFuse(uint256 tokenId1, uint256 tokenId2, uint256 tokenId); event FingerBurn(uint256); event Log(uint gas); struct Finger { bool isRight; bool thumb; bool index; bool middle; bool ring; bool pinky; uint8 thumbDna; uint8 indexDna; uint8 middleDna; uint8 ringDna; uint8 pinkyDna; } Finger[] public fingers; address public owner; function Ownable() public { owner = msg.sender; } function withdraw() external payable { } function getBalance() public view returns (uint) { return address(this).balance; } fallback() external payable { } function readFingersDna(uint256 _tokenId) external view returns(bool, bool, bool, bool, bool, bool, uint8, uint8, uint8, uint8, uint8, uint24){ Finger memory myFinger = fingers[_tokenId]; return (myFinger.isRight, myFinger.thumb, myFinger.index, myFinger.middle, myFinger.ring, myFinger.pinky, myFinger.thumbDna, myFinger.indexDna, myFinger.middleDna, myFinger.ringDna, myFinger.pinkyDna, myFinger.changeCount); } function getFingersByOwner(address _owner) external view returns(uint[] memory) { uint[] memory result = new uint[](ownerFingerCount[_owner]); uint counter = 0; for (uint i = 0; i < fingers.length; i++) { if (fingerToOwner[i] == _owner) { result[counter] = i; counter++; } } return result; } function getFingersByOwner(address _owner) external view returns(uint[] memory) { uint[] memory result = new uint[](ownerFingerCount[_owner]); uint counter = 0; for (uint i = 0; i < fingers.length; i++) { if (fingerToOwner[i] == _owner) { result[counter] = i; counter++; } } return result; } function getFingersByOwner(address _owner) external view returns(uint[] memory) { uint[] memory result = new uint[](ownerFingerCount[_owner]); uint counter = 0; for (uint i = 0; i < fingers.length; i++) { if (fingerToOwner[i] == _owner) { result[counter] = i; counter++; } } return result; } function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } else{isRight = true;} function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function _generateFinger() internal returns(uint256) { bool isRight; bool thumb = false; bool index = false; bool middle = false; bool ring = false; bool pinky = false; uint8 randomFinger = uint8(_random5()); if(_random2() == 0){ isRight = false; } if(randomFinger == 0){ thumb = true; } if(randomFinger == 1){ index = true; } if(randomFinger == 2){ middle = true; } if(randomFinger == 3){ ring = true; } if(randomFinger == 4){ pinky = true; } fingers.push(Finger(isRight, thumb, index, middle, ring, pinky, _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), _generateFingerDna(), 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function generateFingerByOwner(bool _isRight, bool _thumb, bool _index, bool _middle, bool _ring, bool _pinky, uint8 _thumbDna, uint8 _indexDna, uint8 _middleDna, uint8 _ringDna, uint8 _pinkyDna) external returns(uint256){ fingers.push(Finger(_isRight, _thumb, _index, _middle, _ring, _pinky, _thumbDna, _indexDna, _middleDna, _ringDna, _pinkyDna, 0)); uint256 tokenId = fingers.length; fingerToOwner[tokenId] = msg.sender; ownerFingerCount[msg.sender]++; return tokenId; } function _burnFinger(uint256 _tokenId) internal { assert(fingerToOwner[_tokenId] == msg.sender); fingerToOwner[_tokenId] = address(0); } function burnFingerExt(uint256 _tokenId) external { assert(fingerToOwner[_tokenId] == msg.sender); fingerToOwner[_tokenId] = address(0); } function buyFinger() public /*payable*/ { _generateFinger(); } function buyChangeDna(uint256 _tokenId) public payable { _changeDna(_tokenId); } function setFingerPrice(uint _fingerPrice) external /*onlyOwner*/ { fingerPrice = _fingerPrice; } b = _b; a = _a; }
13,193,604
[ 1, 11890, 279, 273, 374, 31, 11890, 324, 273, 30082, 31, 225, 302, 132, 107, 926, 77, 7125, 12792, 343, 7637, 24601, 884, 5011, 697, 524, 132, 107, 270, 19847, 779, 11173, 18022, 619, 949, 6044, 24235, 132, 107, 87, 443, 463, 6582, 431, 7864, 4530, 404, 294, 5605, 12, 69, 33, 20, 16, 324, 33, 7991, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 310, 414, 1748, 291, 4232, 39, 27, 5340, 5549, 288, 203, 377, 203, 565, 871, 1166, 42, 6658, 12, 11890, 5034, 1147, 548, 1769, 203, 565, 871, 478, 6658, 3043, 12, 11890, 5034, 1147, 548, 1769, 203, 565, 871, 478, 6658, 42, 1202, 12, 11890, 5034, 1147, 548, 21, 16, 2254, 5034, 1147, 548, 22, 16, 2254, 5034, 1147, 548, 1769, 203, 565, 871, 478, 6658, 38, 321, 12, 11890, 5034, 1769, 203, 565, 871, 1827, 12, 11890, 16189, 1769, 203, 377, 203, 377, 203, 203, 203, 565, 1958, 478, 6658, 288, 203, 27699, 377, 203, 565, 1426, 353, 4726, 31, 203, 565, 1426, 11156, 31, 203, 565, 1426, 770, 31, 203, 565, 1426, 7689, 31, 203, 565, 1426, 9221, 31, 203, 565, 1426, 293, 754, 93, 31, 203, 377, 203, 565, 2254, 28, 11156, 40, 6582, 31, 203, 565, 2254, 28, 770, 40, 6582, 31, 203, 565, 2254, 28, 7689, 40, 6582, 31, 203, 565, 2254, 28, 9221, 40, 6582, 31, 203, 565, 2254, 28, 293, 754, 93, 40, 6582, 31, 203, 203, 565, 289, 203, 377, 203, 565, 478, 6658, 8526, 1071, 284, 310, 414, 31, 203, 377, 203, 377, 203, 565, 1758, 1071, 3410, 31, 203, 565, 445, 14223, 6914, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 7010, 565, 445, 598, 9446, 1435, 3903, 8843, 429, 288, 203, 565, 289, 203, 203, 565, 445, 2882, 6112, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 1758, 12, 2211, 2934, 2 ]
./full_match/3/0xD7b903AC1D7818b9712162cC47565429A5595EE6/sources/browser/github/NEST-Protocol/NEST-oracle-V3/VoteContract/Nest_3_VoteFactory.sol
Destroy contract address
address _destructionAddress;
8,162,136
[ 1, 10740, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 389, 5489, 313, 4062, 1887, 31, 19694, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BSD-4-Clause pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IOddzOption.sol"; import "./IOddzAsset.sol"; import "../Pool/IOddzLiquidityPoolManager.sol"; import "./IOddzOptionPremiumManager.sol"; import "../IOddzAdministrator.sol"; import "../IOddzSDK.sol"; import "../Oracle/IOddzPriceOracleManager.sol"; import "../Oracle/IOddzIVOracleManager.sol"; import "../Libs/ABDKMath64x64.sol"; import "../Libs/IERC20Extented.sol"; import "./IOddzFeeManager.sol"; contract OddzOptionManager is IOddzOption, AccessControl { using Math for uint256; using SafeERC20 for IERC20Extented; using Address for address; bytes32 public constant TIMELOCKER_ROLE = keccak256("TIMELOCKER_ROLE"); IOddzAsset public assetManager; IOddzLiquidityPoolManager public pool; IOddzPriceOracleManager public oracle; IOddzIVOracleManager public volatility; IOddzOptionPremiumManager public premiumManager; IERC20Extented public token; IOddzFeeManager public oddzFeeManager; Option[] public override options; /** * @dev Transaction Fee definitions */ uint256 public txnFeeAggregate; /** * @dev Settlement Fee definitions */ uint256 public settlementFeeAggregate; /** * @dev Max Deadline in seconds */ uint32 public maxDeadline; /** * @dev SDK contract address */ IOddzSDK public sdk; IOddzAdministrator public administrator; /** * @dev minimum premium */ uint256 public minimumPremium; /** * @dev option transfer map * mapping (optionId => minAmount) */ mapping(uint256 => uint256) public optionTransferMap; constructor( IOddzPriceOracleManager _oracle, IOddzIVOracleManager _iv, IOddzLiquidityPoolManager _pool, IERC20Extented _token, IOddzAsset _assetManager, IOddzOptionPremiumManager _premiumManager, IOddzFeeManager _oddzFeeManager ) { pool = _pool; oracle = _oracle; volatility = _iv; token = _token; assetManager = _assetManager; premiumManager = _premiumManager; oddzFeeManager = _oddzFeeManager; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(TIMELOCKER_ROLE, msg.sender); _setRoleAdmin(TIMELOCKER_ROLE, TIMELOCKER_ROLE); } modifier onlyOwner(address _address) { require(hasRole(DEFAULT_ADMIN_ROLE, _address), "caller has no access to the method"); _; } modifier onlyTimeLocker(address _address) { require(hasRole(TIMELOCKER_ROLE, _address), "caller has no access to the method"); _; } modifier validAmount(uint256 _amount, address _pair) { require(_amount >= assetManager.getPurchaseLimit(_pair), "amount less than purchase limit"); _; } modifier validateOptionParams( OptionType _optionType, address _pair, uint256 _expiration ) { _validAssetPair(_pair); _validExpiration(_expiration, _pair); _; } function _validExpiration(uint256 _expiration, address _pair) private view { require(_expiration <= assetManager.getMaxPeriod(_pair), "Expiration is greater than max expiry"); require(_expiration >= assetManager.getMinPeriod(_pair), "Expiration is less than min expiry"); } function _validAssetPair(address _pair) private view { require(assetManager.getStatusOfPair(_pair) == true, "Invalid Asset pair"); } /** * @notice validate strike price * @param _strike strike price provided by the option buyer * @param _minPrice minumum allowed strike price * @param _maxPrice maximum allowed strike price */ function _validStrike( uint256 _strike, uint256 _minPrice, uint256 _maxPrice ) private pure { require(_strike <= _maxPrice && _strike >= _minPrice, "Strike out of Range"); } /** * @notice validate option premium * @param _value user paid amount * @param _premium option premium */ function _validateOptionAmount(uint256 _value, uint256 _premium) private view { require(_premium >= minimumPremium, "amount is lower than minimum premium"); require(_value >= _premium, "Premium is low"); } /** * @notice get maximum strike price * @param _cp current price of the underlying asset * @param _iv implied volatility of the underlying asset * @param _ivDecimal iv precision * @return oc - over collateralization */ function _getMaxStrikePrice( uint256 _cp, uint256 _iv, uint8 _ivDecimal ) private pure returns (uint256 oc) { // fetch highest call price using IV uint256 ivExp = ABDKMath64x64.mulu(ABDKMath64x64.exp(ABDKMath64x64.divu(_iv, 10**_ivDecimal)), 10**_ivDecimal); oc = (_cp * ivExp) / (10**_ivDecimal); } /** * @notice get minimum strike price * @param _cp current price of the underlying asset * @param _iv implied volatility of the underlying asset * @param _ivDecimal iv precision * @return oc - over collateralization */ function _getMinStrikePrice( uint256 _cp, uint256 _iv, uint8 _ivDecimal ) private pure returns (uint256 oc) { // fetch lowest put price using IV // use negative IV for put uint256 ivExp = ABDKMath64x64.mulu(ABDKMath64x64.exp(-ABDKMath64x64.divu(_iv, 10**_ivDecimal)), 10**_ivDecimal); oc = (_cp * ivExp) / (10**_ivDecimal); } /** * @notice get current price of the given asset * @param _pair asset pair * @return cp - current price of the underlying asset */ function _getCurrentPrice(IOddzAsset.AssetPair memory _pair) private view returns (uint256 cp) { uint8 decimal; // retrieving struct if more than one field is used, to reduce gas for memory storage IOddzAsset.Asset memory primary = assetManager.getAsset(_pair._primary); (cp, decimal) = oracle.getUnderlyingPrice(primary._name, _pair._strike); cp = _updatePrecision(cp, decimal, primary._precision); } /** * @notice get collateral info for option * @param _cp current price of the underlying asset * @param _iv implied volatility of the underlying asset * @param _strike strike price provided by the option buyer * @param _pair Asset pair * @param _ivDecimal iv precision * @return callOverColl - call over collateral * @return putOverColl - put over collateral */ function _getCollateralAmount( uint256 _cp, uint256 _iv, uint256 _strike, address _pair, uint8 _ivDecimal ) private view returns (uint256 callOverColl, uint256 putOverColl) { IOddzAsset.Asset memory primary = assetManager.getAsset(assetManager.getPrimaryFromPair(_pair)); uint256 minAssetPrice = _getMinStrikePrice(_cp, _iv, _ivDecimal); uint256 maxAssetPrice = _getMaxStrikePrice(_cp, _iv, _ivDecimal); _validStrike(_strike, minAssetPrice, maxAssetPrice); // limit call over collateral to _strike i.e. max profit is limited to _strike callOverColl = _updatePrecision(maxAssetPrice.min(_strike), primary._precision, token.decimals()); putOverColl = _updatePrecision(_strike - minAssetPrice, primary._precision, token.decimals()); } function _getLockAmount( uint256 _cp, uint256 _iv, uint256 _strike, address _pair, uint8 _ivDecimal, OptionType _optionType, uint256 _quantity ) private view returns (uint256 lockAmount) { (uint256 callOverColl, uint256 putOverColl) = _getCollateralAmount(_cp, _iv, _strike, _pair, _ivDecimal); lockAmount = _optionType == OptionType.Call ? callOverColl : putOverColl; lockAmount = (lockAmount * _quantity) / 1e18; } function buy( OptionDetails memory _details, uint256 _premiumWithSlippage, address _buyer ) external override validateOptionParams(_details._optionType, _details._pair, _details._expiration) validAmount(_details._amount, _details._pair) returns (uint256 optionId) { address buyer_ = msg.sender == address(sdk) ? _buyer : msg.sender; optionId = _createOption(_details, _premiumWithSlippage, buyer_); } /** * @notice Create option * @param _details option buy details * @param _premiumWithSlippage Options details * @param _buyer Address of buyer * @return optionId newly created Option Id */ function _createOption( OptionDetails memory _details, uint256 _premiumWithSlippage, address _buyer ) private returns (uint256 optionId) { PremiumResult memory premiumResult = getPremium(_details, _buyer); require(_premiumWithSlippage >= premiumResult.optionPremium, "Premium crossed slippage tolerance"); uint256 cp = _getCurrentPrice(assetManager.getPair(_details._pair)); _validateOptionAmount( token.allowance(_buyer, address(this)), premiumResult.optionPremium + premiumResult.txnFee ); uint256 lockAmount = _getLockAmount( cp, premiumResult.iv, _details._strike, _details._pair, premiumResult.ivDecimal, _details._optionType, _details._amount ); optionId = options.length; Option memory option = Option( State.Active, _buyer, _details._strike, _details._amount, lockAmount, premiumResult.optionPremium, _details._expiration + block.timestamp, _details._pair, _details._optionType ); options.push(option); IOddzLiquidityPoolManager.LiquidityParams memory liquidityParams = IOddzLiquidityPoolManager.LiquidityParams( lockAmount, _details._expiration, _details._pair, _details._optionModel, _details._optionType ); pool.lockLiquidity(optionId, liquidityParams, premiumResult.optionPremium); txnFeeAggregate += premiumResult.txnFee; token.safeTransferFrom(_buyer, address(pool), premiumResult.optionPremium); token.safeTransferFrom(_buyer, address(this), premiumResult.txnFee); emit Buy( optionId, _buyer, _details._optionModel, premiumResult.txnFee, premiumResult.optionPremium + premiumResult.txnFee, _details._pair ); } /** * @notice Used for getting the actual options prices * @param _option Option details * @param _buyer Address of option buyer * @return premiumResult Premium, iv Details */ function getPremium(OptionDetails memory _option, address _buyer) public view override validateOptionParams(_option._optionType, _option._pair, _option._expiration) returns (PremiumResult memory premiumResult) { (premiumResult.ivDecimal, premiumResult.iv, premiumResult.optionPremium) = _getOptionPremiumDetails(_option); premiumResult.txnFee = _getTransactionFee(premiumResult.optionPremium, _buyer); } function _getOptionPremiumDetails(OptionDetails memory optionDetails) private view returns ( uint8 ivDecimal, uint256 iv, uint256 optionPremium ) { IOddzAsset.AssetPair memory pair = assetManager.getPair(optionDetails._pair); uint256 price = _getCurrentPrice(pair); (iv, ivDecimal) = volatility.calculateIv( pair._primary, pair._strike, optionDetails._expiration, price, optionDetails._strike ); optionPremium = premiumManager.getPremium( optionDetails._optionType == IOddzOption.OptionType.Call ? true : false, assetManager.getPrecision(pair._primary), ivDecimal, price, optionDetails._strike, optionDetails._expiration, optionDetails._amount, iv, optionDetails._optionModel ); // convert to USD price precision uint8 _decimal = assetManager.getPrecision(pair._primary); optionPremium = _updatePrecision(optionPremium, _decimal, token.decimals()); } /** * @notice Used for cash settlement excerise for an active option * @param _optionId Option id */ function exercise(uint256 _optionId) external override { Option storage option = options[_optionId]; require(option.expiration >= block.timestamp, "Option has expired"); require(option.holder == msg.sender, "Invalid Caller"); require(option.state == State.Active, "Invalid state"); option.state = State.Exercised; (uint256 profit, uint256 settlementFee) = _getProfit(_optionId); pool.send(_optionId, option.holder, profit); emit Exercise(_optionId, profit, settlementFee, ExcerciseType.Cash); } /** * @notice Used for physical settlement excerise for an active option * @param _optionId Option id * @param _deadline Deadline until which txn does not revert * @param _minAmountOut Min output tokens */ function exerciseUA( uint256 _optionId, uint32 _deadline, uint16 _minAmountOut ) external override { require(_deadline <= maxDeadline, "Deadline input is more than maximum limit allowed"); Option storage option = options[_optionId]; require(option.expiration >= block.timestamp, "Option has expired"); require(option.holder == msg.sender, "Invalid Caller"); require(option.state == State.Active, "Invalid state"); option.state = State.Exercised; (uint256 profit, uint256 settlementFee) = _getProfit(_optionId); IOddzAsset.AssetPair memory pair = assetManager.getPair(option.pair); pool.sendUA(_optionId, option.holder, profit, pair._primary, pair._strike, _deadline, _minAmountOut); emit Exercise(_optionId, profit, settlementFee, ExcerciseType.Physical); } function enableOptionTransfer(uint256 _optionId, uint256 _minAmount) external { Option storage option = options[_optionId]; require( option.expiration > (block.timestamp + assetManager.getMinPeriod(option.pair)), "Option not eligble for transfer" ); require(option.holder == msg.sender, "Invalid Caller"); require(option.state == State.Active, "Invalid state"); require(_minAmount >= minimumPremium, "amount is lower than minimum premium"); optionTransferMap[_optionId] = _minAmount; emit OptionTransferEnabled(_optionId, _minAmount); } function optionTransfer( uint256 _optionId, address _newOwner, uint256 _minAmount ) external { Option storage option = options[_optionId]; require( option.expiration > (block.timestamp + assetManager.getMinPeriod(option.pair)), "Option not eligble for transfer" ); uint256 minAmount = optionTransferMap[_optionId]; require(minAmount > 0, "Option not enabled for transfer"); require(minAmount == _minAmount, "Invalid negotiated amount"); require(option.state == State.Active, "Invalid state"); require(option.holder != msg.sender && option.holder != _newOwner, "Self option transfer is not allowed"); // once transfer initiated update option tranfer map delete optionTransferMap[_optionId]; uint256 transferFee = _getTransactionFee(minAmount, _newOwner); txnFeeAggregate += transferFee; _validateOptionAmount(token.allowance(msg.sender, address(this)), minAmount + transferFee); token.safeTransferFrom(msg.sender, option.holder, minAmount); token.safeTransferFrom(msg.sender, address(this), transferFee); address oldHolder = option.holder; option.holder = _newOwner; emit OptionTransfer(_optionId, oldHolder, _newOwner, minAmount, transferFee); } /** * @notice Transaction fee calculation for the option premium * @param _amount Option premium * @param _buyer Option buyer address * @return txnFee Transaction Fee */ function _getTransactionFee(uint256 _amount, address _buyer) private view returns (uint256 txnFee) { txnFee = ((_amount * oddzFeeManager.getTransactionFee(_buyer)) / (100 * 10**oddzFeeManager.decimals())); } /** * @notice Sends profits in USD from the USD pool to an option holder's address * @param _optionId ID of the option */ function _getProfit(uint256 _optionId) private returns (uint256 profit, uint256 settlementFee) { Option memory option = options[_optionId]; IOddzAsset.AssetPair memory pair = assetManager.getPair(option.pair); uint256 _cp = _getCurrentPrice(pair); if (option.optionType == OptionType.Call) { require(option.strike <= _cp, "Call option: Current price is too low"); profit = (_cp - option.strike) * option.amount; } else { require(option.strike >= _cp, "Put option: Current price is too high"); profit = (option.strike - _cp) * option.amount; } // amount in wei profit = profit / 1e18; // convert profit to usd decimals profit = _updatePrecision(profit, assetManager.getPrecision(pair._primary), token.decimals()); if (profit > option.lockedAmount) profit = option.lockedAmount; settlementFee = ((profit * oddzFeeManager.getSettlementFee(msg.sender)) / (100 * 10**oddzFeeManager.decimals())); settlementFeeAggregate += settlementFee; token.safeTransferFrom(msg.sender, address(this), settlementFee); } /** * @notice Unlock funds locked in the expired options * @param _optionId ID of the option */ function unlock(uint256 _optionId) public { Option storage option = options[_optionId]; require(option.expiration < block.timestamp, "Option has not expired yet"); require(option.state == State.Active, "Option is not active"); option.state = State.Expired; pool.unlockLiquidity(_optionId); emit Expire(_optionId, option.premium); } /** * @notice Unlocks an array of options * @param _optionIds array of options */ function unlockAll(uint256[] calldata _optionIds) external { uint256 arrayLength = _optionIds.length; for (uint256 i = 0; i < arrayLength; i++) { unlock(_optionIds[i]); } } /** * @notice sets maximum deadline for DEX swap * @param _deadline maximum swap transaction time */ function setMaxDeadline(uint32 _deadline) external onlyOwner(msg.sender) { maxDeadline = _deadline; } /** * @notice sets SDK address * @param _sdk Oddz SDK address */ function setSdk(IOddzSDK _sdk) external onlyTimeLocker(msg.sender) { require(address(_sdk).isContract(), "invalid SDK contract address"); sdk = _sdk; } /** * @notice sets administrator address * @param _administrator Oddz administrator address */ function setAdministrator(IOddzAdministrator _administrator) external onlyTimeLocker(msg.sender) { require(address(_administrator).isContract(), "invalid administrator contract address"); // Set token allowance of previous administrator to 0 if (address(administrator) != address(0)) token.safeApprove(address(administrator), 0); administrator = _administrator; // Approve token transfer to administrator contract token.safeApprove(address(administrator), type(uint256).max); } function setMinimumPremium(uint256 _amount) external onlyTimeLocker(msg.sender) { uint256 amount = _amount / 10**token.decimals(); require(amount >= 1 && amount < 50, "invalid minimum premium"); minimumPremium = _amount; } function setTimeLocker(address _address) external { require(_address != address(0), "Invalid timelocker address"); grantRole(TIMELOCKER_ROLE, _address); } function removeTimeLocker(address _address) external { revokeRole(TIMELOCKER_ROLE, _address); } /** * @notice transfer transaction fee to beneficiary */ function transferTxnFeeToBeneficiary(uint256 _minAmountsOut) external onlyOwner(msg.sender) { uint256 txnFee = txnFeeAggregate; txnFeeAggregate = 0; require(address(administrator) != address(0), "invalid administrator address"); administrator.deposit(txnFee, IOddzAdministrator.DepositType.Transaction, _minAmountsOut); } /** * @notice transfer settlement fee to beneficiary */ function transferSettlementFeeToBeneficiary(uint256 _minAmountsOut) external onlyOwner(msg.sender) { uint256 settlementFee = settlementFeeAggregate; settlementFeeAggregate = 0; require(address(administrator) != address(0), "invalid administrator address"); administrator.deposit(settlementFee, IOddzAdministrator.DepositType.Settlement, _minAmountsOut); } /** * @notice update precision from current to required * @param _value value to be precision updated * @param _current current precision * @param _required required precision * @return result updated _value */ function _updatePrecision( uint256 _value, uint8 _current, uint8 _required ) private pure returns (uint256 result) { if (_required > _current) result = (_value * (10**_required)) / (10**_current); else result = (_value * (10**_current)) / (10**_required); } }
once transfer initiated update option tranfer map
function optionTransfer( uint256 _optionId, address _newOwner, uint256 _minAmount ) external { Option storage option = options[_optionId]; require( option.expiration > (block.timestamp + assetManager.getMinPeriod(option.pair)), "Option not eligble for transfer" ); uint256 minAmount = optionTransferMap[_optionId]; require(minAmount > 0, "Option not enabled for transfer"); require(minAmount == _minAmount, "Invalid negotiated amount"); require(option.state == State.Active, "Invalid state"); require(option.holder != msg.sender && option.holder != _newOwner, "Self option transfer is not allowed"); delete optionTransferMap[_optionId]; uint256 transferFee = _getTransactionFee(minAmount, _newOwner); txnFeeAggregate += transferFee; _validateOptionAmount(token.allowance(msg.sender, address(this)), minAmount + transferFee); token.safeTransferFrom(msg.sender, option.holder, minAmount); token.safeTransferFrom(msg.sender, address(this), transferFee); address oldHolder = option.holder; option.holder = _newOwner; emit OptionTransfer(_optionId, oldHolder, _newOwner, minAmount, transferFee); }
1,758,466
[ 1, 8243, 7412, 27183, 1089, 1456, 13637, 586, 852, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1456, 5912, 12, 203, 3639, 2254, 5034, 389, 3482, 548, 16, 203, 3639, 1758, 389, 2704, 5541, 16, 203, 3639, 2254, 5034, 389, 1154, 6275, 203, 565, 262, 3903, 288, 203, 3639, 2698, 2502, 1456, 273, 702, 63, 67, 3482, 548, 15533, 203, 3639, 2583, 12, 203, 5411, 1456, 18, 19519, 405, 261, 2629, 18, 5508, 397, 3310, 1318, 18, 588, 2930, 5027, 12, 3482, 18, 6017, 13, 3631, 203, 5411, 315, 1895, 486, 415, 360, 7119, 364, 7412, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 1131, 6275, 273, 1456, 5912, 863, 63, 67, 3482, 548, 15533, 203, 3639, 2583, 12, 1154, 6275, 405, 374, 16, 315, 1895, 486, 3696, 364, 7412, 8863, 203, 3639, 2583, 12, 1154, 6275, 422, 389, 1154, 6275, 16, 315, 1941, 17257, 10206, 3844, 8863, 203, 3639, 2583, 12, 3482, 18, 2019, 422, 3287, 18, 3896, 16, 315, 1941, 919, 8863, 203, 3639, 2583, 12, 3482, 18, 4505, 480, 1234, 18, 15330, 597, 1456, 18, 4505, 480, 389, 2704, 5541, 16, 315, 10084, 1456, 7412, 353, 486, 2935, 8863, 203, 203, 3639, 1430, 1456, 5912, 863, 63, 67, 3482, 548, 15533, 203, 203, 3639, 2254, 5034, 7412, 14667, 273, 389, 588, 3342, 14667, 12, 1154, 6275, 16, 389, 2704, 5541, 1769, 203, 3639, 7827, 14667, 11490, 1011, 7412, 14667, 31, 203, 203, 3639, 389, 5662, 1895, 6275, 12, 2316, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 13, 3631, 1131, 6275, 397, 7412, 14667, 1769, 203, 203, 3639, 1147, 18, 4626, 5912, 1265, 2 ]
./full_match/8453/0x0972892bDa852a6A8C2346Bc552f7782E22D55a9/sources/contracts/providers/TokenVault.sol
* deposit This method will enable root key holders to deposit ERC20s into the trust. This method operates under the assumption of approval. @param keyId the ID of the key that the depositor is using. @param token the address of the ERC20 token contract. @param amount the amount to deposit/ stop right now if the message sender doesn't hold the key generate the token arn
function deposit(uint256 keyId, address token, uint256 amount) external { require(IKeyVault(locksmith.getKeyVault()).keyBalanceOf(msg.sender, keyId, false) > 0, 'KEY_NOT_HELD'); bytes32 tokenArn = AssetResourceName.AssetType({ contractAddress: token, tokenStandard: 20, id: 0 }).arn(); "INSUFFICIENT_TOKENS"); witnessedTokenAddresses[trustId].add(token); }
11,550,899
[ 1, 323, 1724, 1220, 707, 903, 4237, 1365, 498, 366, 4665, 358, 443, 1724, 4232, 39, 3462, 87, 1368, 326, 10267, 18, 1220, 707, 2255, 815, 3613, 326, 24743, 434, 23556, 18, 225, 30914, 326, 1599, 434, 326, 498, 716, 326, 443, 1724, 280, 353, 1450, 18, 225, 1147, 326, 1758, 434, 326, 4232, 39, 3462, 1147, 6835, 18, 225, 3844, 326, 3844, 358, 443, 1724, 19, 2132, 2145, 2037, 309, 326, 883, 5793, 3302, 1404, 6887, 326, 498, 2103, 326, 1147, 26399, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 30914, 16, 1758, 1147, 16, 2254, 5034, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 45, 653, 12003, 12, 739, 4808, 483, 18, 588, 653, 12003, 1435, 2934, 856, 13937, 951, 12, 3576, 18, 15330, 16, 30914, 16, 629, 13, 405, 374, 16, 296, 3297, 67, 4400, 67, 44, 5192, 8284, 203, 203, 3639, 1731, 1578, 1147, 5046, 273, 10494, 19327, 18, 6672, 559, 12590, 203, 5411, 6835, 1887, 30, 1147, 16, 7010, 5411, 1147, 8336, 30, 4200, 16, 7010, 5411, 612, 30, 374, 7010, 3639, 289, 2934, 1303, 5621, 203, 203, 203, 5411, 315, 706, 6639, 42, 1653, 7266, 2222, 67, 8412, 55, 8863, 203, 540, 203, 540, 203, 3639, 31039, 23712, 730, 1345, 7148, 63, 21879, 548, 8009, 1289, 12, 2316, 1769, 203, 540, 203, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xff4c447ae1212E96De4dcFfc0EDe7e309512605B/sources/project_/contracts/1inchproxy.sol
require( order.expiration >= block.timestamp, "Order: Cannot execute an expired order" );
function execute( bytes calldata oneInchCallData, address srcTokenAddr, address dstTokenAddr, uint256 srcAmount, uint256 minReturnAmount, uint256 period ) external payable { Order storage order = orders; IERC20 srcToken = IERC20(srcTokenAddr); IERC20 dstToken = IERC20(dstTokenAddr); require( msg.value > (srcToken.isETH() ? srcAmount : 0), "Tx impossible: Not enough funds to pay reward" ); uint256 execReward = srcToken.isETH() ? msg.value.sub(srcAmount) : msg.value; uint256 expiration = block.timestamp + period; require( expiration > block.timestamp, "Order: Expiration is before current datetime" ); require( order.state == State.Pending, "Order: Can execute only pending orders" ); ( IOneInchCaller caller, IOneInchExchange.SwapDescription memory desc, IOneInchCaller.CallDescription[] memory calls ) = abi.decode( oneInchCallData[4:], ( IOneInchCaller, IOneInchExchange.SwapDescription, IOneInchCaller.CallDescription[] ) ); require( desc.guaranteedAmount >= order.minReturnAmount, "desc.guaranteedAmount is less than order.minReturnAmount" ); require( address(desc.srcToken) == address(order.srcToken) && address(desc.dstToken) == address(order.dstToken) && desc.dstReceiver == order.beneficiary, "Calldata is not correct" ); uint256 msgValue = order.srcToken.isETH() ? order.srcAmount : 0; if (!srcToken.isETH()) { srcToken.safeTransferFrom(msg.sender, address(this), srcAmount); srcToken.uniApprove(address(oneInchExchange), srcAmount); } caller, desc, calls ); require( returnAmount >= order.minReturnAmount, "returnAmount is less than order.minReturnAmount" ); order.state = State.Fulfilled; payable(msg.sender).transfer(order.execReward);
9,530,366
[ 1, 6528, 12, 377, 1353, 18, 19519, 1545, 1203, 18, 5508, 16, 377, 315, 2448, 30, 14143, 1836, 392, 7708, 1353, 6, 11272, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 12, 203, 3639, 203, 3639, 1731, 745, 892, 1245, 382, 343, 1477, 751, 16, 203, 3639, 1758, 1705, 1345, 3178, 16, 203, 3639, 1758, 3046, 1345, 3178, 16, 203, 3639, 2254, 5034, 1705, 6275, 16, 203, 3639, 2254, 5034, 1131, 990, 6275, 16, 203, 3639, 2254, 5034, 3879, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 4347, 2502, 1353, 273, 11077, 31, 203, 203, 3639, 467, 654, 39, 3462, 1705, 1345, 273, 467, 654, 39, 3462, 12, 4816, 1345, 3178, 1769, 203, 3639, 467, 654, 39, 3462, 3046, 1345, 273, 467, 654, 39, 3462, 12, 11057, 1345, 3178, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 405, 261, 4816, 1345, 18, 291, 1584, 44, 1435, 692, 1705, 6275, 294, 374, 3631, 203, 5411, 315, 4188, 23343, 30, 2288, 7304, 284, 19156, 358, 8843, 19890, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 1196, 17631, 1060, 273, 1705, 1345, 18, 291, 1584, 44, 1435, 203, 5411, 692, 1234, 18, 1132, 18, 1717, 12, 4816, 6275, 13, 203, 5411, 294, 1234, 18, 1132, 31, 203, 203, 3639, 2254, 5034, 7686, 273, 1203, 18, 5508, 397, 3879, 31, 203, 3639, 2583, 12, 203, 5411, 7686, 405, 1203, 18, 5508, 16, 203, 5411, 315, 2448, 30, 31017, 353, 1865, 783, 3314, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 1353, 18, 2019, 422, 3287, 18, 8579, 16, 203, 5411, 315, 2448, 30, 4480, 1836, 1338, 4634, 11077, 6, 203, 3639, 11272, 203, 203, 3639, 261, 203, 5411, 467, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-03 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @dev ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } /** * @dev ERC-721 interface for accepting safe transfers. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. * @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); } /** * @dev Math operations with safety checks that throw on error. */ library SafeMath { string constant OVERFLOW = "008001"; string constant SUBTRAHEND_GREATER_THEN_MINUEND = "008002"; string constant DIVISION_BY_ZERO = "008003"; /** * @dev Multiplies two numbers, reverts on overflow. * @param _factor1 Factor number. * @param _factor2 Factor number. * @return product The product of the two factors. */ function mul( uint256 _factor1, uint256 _factor2 ) internal pure returns (uint256 product) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. if (_factor1 == 0) { return 0; } product = _factor1 * _factor2; require(product / _factor1 == _factor2, OVERFLOW); } /** * @dev Integer division of two numbers, truncating the quotient, reverts on division by zero. * @param _dividend Dividend number. * @param _divisor Divisor number. * @return quotient The quotient. */ function div( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 quotient) { // Solidity automatically asserts when dividing by 0, using all gas. require(_divisor > 0, DIVISION_BY_ZERO); quotient = _dividend / _divisor; // assert(_dividend == _divisor * quotient + _dividend % _divisor); // There is no case in which this doesn't hold. } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). * @param _minuend Minuend number. * @param _subtrahend Subtrahend number. * @return difference Difference. */ function sub( uint256 _minuend, uint256 _subtrahend ) internal pure returns (uint256 difference) { require(_subtrahend <= _minuend, SUBTRAHEND_GREATER_THEN_MINUEND); difference = _minuend - _subtrahend; } /** * @dev Adds two numbers, reverts on overflow. * @param _addend1 Number. * @param _addend2 Number. * @return sum Sum. */ function add( uint256 _addend1, uint256 _addend2 ) internal pure returns (uint256 sum) { sum = _addend1 + _addend2; require(sum >= _addend1, OVERFLOW); } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), reverts when * dividing by zero. * @param _dividend Number. * @param _divisor Number. * @return remainder Remainder. */ function mod( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 remainder) { require(_divisor != 0, DIVISION_BY_ZERO); remainder = _dividend % _divisor; } } /** * @dev A standard for detecting smart contract interfaces. * See: https://eips.ethereum.org/EIPS/eip-165. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } /** * @dev Implementation of standard for detect smart contract interfaces. */ contract SupportsInterface is ERC165 { mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external override view returns (bool) { return supportedInterfaces[_interfaceID]; } } /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. * @return addressCheck True if _addr is a contract, false if not. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // 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; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROWED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) private ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; // /** // * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are // * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any // * number of NFTs may be created and assigned without emitting Transfer. At the time of any // * transfer, the approved address for that NFT (if any) is reset to none. // * @param _from Sender of NFT (if address is zero address it indicates token creation). // * @param _to Receiver of NFT (if address is zero address it indicates token destruction). // * @param _tokenId The NFT that got transfered. // */ // event Transfer( // address indexed _from, // address indexed _to, // uint256 indexed _tokenId // ); // /** // * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero // * address indicates there is no approved address. When a Transfer event emits, this also // * indicates that the approved address for that NFT (if any) is reset to none. // * @param _owner Owner of NFT. // * @param _approved Address that we are approving. // * @param _tokenId NFT which we are approving. // */ // event Approval( // address indexed _owner, // address indexed _approved, // uint256 indexed _tokenId // ); // /** // * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage // * all NFTs of the owner. // * @param _owner Owner of NFT. // * @param _operator Address to which we are setting operator rights. // * @param _approved Status of operator rights(true if operator rights are given and false if // * revoked). // */ // event ApprovalForAll( // address indexed _owner, // address indexed _operator, // bool _approved // ); /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROWED_OR_OPERATOR ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; } /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external override { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they maybe be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external override canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, IS_OWNER); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external override { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external override view returns (uint256) { require(_owner != address(0), ZERO_ADDRESS); return _getOwnerNFTCount(_owner); } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return _owner Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0), NOT_VALID_NFT); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external override view returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal virtual { require(_to != address(0), ZERO_ADDRESS); require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external burn * function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage (gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal virtual view returns (uint256) { return ownerToNFTokenCount[_owner]; } /** * @dev Actually perform the safeTransferFrom. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval( uint256 _tokenId ) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } } /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */ contract NFTokenMetadata is NFToken, ERC721Metadata { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } } /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. * @return Total supply of NFTs. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFTokenEnumerable is NFToken, ERC721Enumerable { string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } } /** * @dev The contract has an owner address, and provides basic authorization control which * simplifies the implementation of user permissions. */ contract Ownable { /** * @dev Error constants. */ string public constant NOT_CURRENT_OWNER = "018001"; string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002"; /** * @dev Current owner address. */ address public owner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The constructor sets the original `owner` of the contract to the sender account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, NOT_CURRENT_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), CANNOT_TRANSFER_TO_ZERO_ADDRESS); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } interface IMintable { function mintFor( address to, uint256 id, bytes calldata blueprint ) external; } library Bytes { /** * @dev Converts a `uint256` to a `string`. * via OraclizeAPI - MIT licence * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol */ function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } bytes constant alphabet = "0123456789abcdef"; /** * 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( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function substring( bytes memory strBytes, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { result = result * 10 + (val - 48); } } return result; } } library Minting { // Split the minting blob into token_id and blueprint portions // {token_id}:{blueprint} function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = Bytes.indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } } abstract contract Mintable is Ownable, IMintable { address public imx; mapping(uint256 => bytes) public blueprints; event AssetMinted(address to, uint256 id, bytes blueprint); constructor(address _owner, address _imx) { imx = _imx; require(_owner != address(0), "Owner must not be empty"); transferOwnership(_owner); } modifier onlyIMX() { require(msg.sender == imx, "Function can only be called by IMX"); _; } function mintFor( address user, uint256 quantity, bytes calldata mintingBlob ) external override onlyIMX { require(quantity == 1, "Mintable: invalid quantity"); (uint256 id, bytes memory blueprint) = Minting.split(mintingBlob); _mintFor(user, id, blueprint); blueprints[id] = blueprint; emit AssetMinted(user, id, blueprint); } function _mintFor( address to, uint256 id, bytes memory blueprint ) internal virtual; } contract ArtGalleryTokenImx is NFTokenEnumerable, NFTokenMetadata, Ownable, Mintable { /** * Immutable support */ /** * @dev Contract constructor. Sets metadata extension `name` and `symbol`. * @param _imx immutable contract address */ constructor(address _imx) public Mintable(msg.sender, _imx) { nftName = "ArtGallery"; nftSymbol = "ArtGallery"; publisher = msg.sender; //publisher == owner == contract deployer _own_address = address(this); } /** * @dev mint implementation * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function __mint( address _to, uint256 _tokenId, string memory _uri ) internal { super._mint(_to, _tokenId); super._setTokenUri(_tokenId, _uri); } /** * @dev internal mint function to be called from mintFor called by immutable contract * @param to address that will own the minted NFT * @param id token id of the NFT to be minted. * @param blueprint bytes representing NFT uri string. */ function _mintFor( address to, uint256 id, bytes memory blueprint ) internal override { string memory uri = string(blueprint); __mint(to, id, uri); } /** * ArtGalleryToken */ address public _own_address; address publisher = 0x0000000000000000000000000000000000000000; address bankContract = 0x0000000000000000000000000000000000000000; modifier bankOrPublisher() { require( (msg.sender == publisher) || (msg.sender == bankContract && isContract(msg.sender)), "only bank or publisher can call this function" ); _; } modifier onlyPublisher() { require( msg.sender == publisher, "only publisher can call this function" ); _; } modifier onlyBankContract() { require( msg.sender == bankContract && isContract(msg.sender), "only bank can call this function" ); _; } /** * @dev not bullet-proof check, but additional measure, actually we require specific (contract) address, * which is key (see onlyBankContract) */ function isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } /** * @dev only to be used if you do not have minted tokens, * i.e. what to change name& symbol for cotnract without assets * all minted tokens will disappear */ function setNFTName(string calldata new_name) external onlyOwner { nftName = new_name; } /** * @dev only to be used if you do not have minted tokens, * i.e. what to change name& symbol for cotnract without assets * all minted tokens will disappear */ function setNFTSymbol(string calldata new_symbol) external onlyOwner { nftSymbol = new_symbol; } function transferPublishRight(address newPublisher) external onlyOwner { publisher = newPublisher; } function getPublisher() public view returns (address) { return publisher; } function transferBankRight(address newBankContract) external onlyOwner { bankContract = newBankContract; } function getBankContract() public view returns (address) { return bankContract; } /** * @dev returns contract balance */ function getContractBalance() public view returns (uint256) { return address(this).balance; } /** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function mint( address _to, uint256 _tokenId, string calldata _uri ) external bankOrPublisher { __mint(_to, _tokenId, _uri); } /** * @dev Removes a NFT from owner. * @param _tokenId Which NFT we want to remove. */ function burn(uint256 _tokenId) external bankOrPublisher { super._burn(_tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint(address _to, uint256 _tokenId) internal virtual override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._mint(_to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn(uint256 _tokenId) internal virtual override(NFTokenMetadata, NFTokenEnumerable) { NFTokenEnumerable._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken(address _from, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._removeNFToken(_from, _tokenId); } /** * @dev Assigns a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken(address _to, uint256 _tokenId) internal override(NFToken, NFTokenEnumerable) { NFTokenEnumerable._addNFToken(_to, _tokenId); } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount(address _owner) internal view override(NFToken, NFTokenEnumerable) returns (uint256) { return NFTokenEnumerable._getOwnerNFTCount(_owner); } }
* Immutable support/* @dev Contract constructor. Sets metadata extension `name` and `symbol`. @param _imx immutable contract address/
function _mintFor( address to, uint256 id, bytes memory blueprint ) internal virtual; } contract ArtGalleryTokenImx is NFTokenEnumerable, NFTokenMetadata, Ownable, Mintable constructor(address _imx) public Mintable(msg.sender, _imx) { nftName = "ArtGallery"; nftSymbol = "ArtGallery"; _own_address = address(this); }
10,392,914
[ 1, 16014, 2865, 19, 225, 13456, 3885, 18, 11511, 1982, 2710, 1375, 529, 68, 471, 1375, 7175, 8338, 225, 389, 381, 92, 11732, 6835, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 81, 474, 1290, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 1731, 3778, 13712, 203, 565, 262, 2713, 5024, 31, 203, 97, 203, 203, 203, 16351, 9042, 18511, 1345, 1170, 92, 353, 203, 565, 423, 42, 1345, 3572, 25121, 16, 203, 565, 423, 42, 1345, 2277, 16, 203, 565, 14223, 6914, 16, 203, 565, 490, 474, 429, 203, 565, 3885, 12, 2867, 389, 381, 92, 13, 1071, 490, 474, 429, 12, 3576, 18, 15330, 16, 389, 381, 92, 13, 288, 203, 3639, 290, 1222, 461, 273, 315, 4411, 18511, 14432, 203, 3639, 290, 1222, 5335, 273, 315, 4411, 18511, 14432, 203, 3639, 389, 995, 67, 2867, 273, 1758, 12, 2211, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./RoleAware.sol"; import "./Fund.sol"; import "./CrossMarginTrading.sol"; import "../libraries/IncentiveReporter.sol"; /** @title Here we support staking for MFI incentives as well as staking to perform the maintenance role. */ contract Admin is RoleAware { /// Margenswap (MFI) token address address public immutable MFI; mapping(address => uint256) public stakes; uint256 public totalStakes; uint256 public constant mfiStakeTranche = 1; uint256 public maintenanceStakePerBlock = 15 ether; mapping(address => address) public nextMaintenanceStaker; mapping(address => mapping(address => bool)) public maintenanceDelegateTo; address public currentMaintenanceStaker; address public prevMaintenanceStaker; uint256 public currentMaintenanceStakerStartBlock; address public immutable lockedMFI; constructor( address _MFI, address _lockedMFI, address lockedMFIDelegate, address _roles ) RoleAware(_roles) { MFI = _MFI; lockedMFI = _lockedMFI; // for initialization purposes and to ensure availability of service // the team's locked MFI participate in maintenance staking only // (not in the incentive staking part) // this implies some trust of the team to execute, which we deem reasonable // since the locked stake is temporary and diminishing as well as the fact // that the team is heavily invested in the protocol and incentivized // by fees like any other maintainer // furthermore others could step in to liquidate via the attacker route // and take away the team fees if they were delinquent nextMaintenanceStaker[_lockedMFI] = _lockedMFI; currentMaintenanceStaker = _lockedMFI; prevMaintenanceStaker = _lockedMFI; maintenanceDelegateTo[_lockedMFI][lockedMFIDelegate]; currentMaintenanceStakerStartBlock = block.number; } /// Maintence stake setter function setMaintenanceStakePerBlock(uint256 amount) external onlyOwnerExec { maintenanceStakePerBlock = amount; } function _stake(address holder, uint256 amount) internal { Fund(fund()).depositFor(holder, MFI, amount); stakes[holder] += amount; totalStakes += amount; IncentiveReporter.addToClaimAmount(MFI, holder, amount); } /// Deposit a stake for sender function depositStake(uint256 amount) external { _stake(msg.sender, amount); } function _withdrawStake( address holder, uint256 amount, address recipient ) internal { // overflow failure desirable stakes[holder] -= amount; totalStakes -= amount; Fund(fund()).withdraw(MFI, recipient, amount); IncentiveReporter.subtractFromClaimAmount(MFI, holder, amount); } /// Withdraw stake for sender function withdrawStake(uint256 amount) external { require( !isAuthorizedStaker(msg.sender), "You can't withdraw while you're authorized staker" ); _withdrawStake(msg.sender, amount, msg.sender); } /// Deposit maintenance stake function depositMaintenanceStake(uint256 amount) external { require( amount + stakes[msg.sender] >= maintenanceStakePerBlock, "Insufficient stake to call even one block" ); _stake(msg.sender, amount); if (nextMaintenanceStaker[msg.sender] == address(0)) { nextMaintenanceStaker[msg.sender] = getUpdatedCurrentStaker(); nextMaintenanceStaker[prevMaintenanceStaker] = msg.sender; } } function getMaintenanceStakerStake(address staker) public view returns (uint256) { if (staker == lockedMFI) { return IERC20(MFI).balanceOf(lockedMFI) / 2; } else { return stakes[staker]; } } function getUpdatedCurrentStaker() public returns (address) { uint256 currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if ( (block.number - currentMaintenanceStakerStartBlock) * maintenanceStakePerBlock >= currentStake ) { currentMaintenanceStakerStartBlock = block.number; prevMaintenanceStaker = currentMaintenanceStaker; currentMaintenanceStaker = nextMaintenanceStaker[ currentMaintenanceStaker ]; currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if (maintenanceStakePerBlock > currentStake) { // delete current from daisy chain address nextOne = nextMaintenanceStaker[currentMaintenanceStaker]; nextMaintenanceStaker[prevMaintenanceStaker] = nextOne; nextMaintenanceStaker[currentMaintenanceStaker] = address(0); currentMaintenanceStaker = nextOne; currentStake = getMaintenanceStakerStake( currentMaintenanceStaker ); } } return currentMaintenanceStaker; } function viewCurrentMaintenanceStaker() public view returns (address staker, uint256 startBlock) { staker = currentMaintenanceStaker; uint256 currentStake = getMaintenanceStakerStake(staker); startBlock = currentMaintenanceStakerStartBlock; if ( (block.number - startBlock) * maintenanceStakePerBlock >= currentStake ) { staker = nextMaintenanceStaker[staker]; currentStake = getMaintenanceStakerStake(staker); startBlock = block.number; if (maintenanceStakePerBlock > currentStake) { staker = nextMaintenanceStaker[staker]; } } } /// Add a delegate for staker function addDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = true; } /// Remove a delegate for staker function removeDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = false; } function isAuthorizedStaker(address caller) public returns (bool isAuthorized) { address currentStaker = getUpdatedCurrentStaker(); isAuthorized = currentStaker == caller || maintenanceDelegateTo[currentStaker][caller]; } /// Penalize a staker function penalizeMaintenanceStake( address maintainer, uint256 penalty, address recipient ) external returns (uint256 stakeTaken) { require( isStakePenalizer(msg.sender), "msg.sender not authorized to penalize stakers" ); if (penalty > stakes[maintainer]) { stakeTaken = stakes[maintainer]; } else { stakeTaken = penalty; } _withdrawStake(maintainer, stakeTaken, recipient); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; /// @title Base lending behavior abstract contract BaseLending { uint256 constant FP48 = 2**48; uint256 constant ACCUMULATOR_INIT = 10**18; uint256 constant hoursPerYear = 365 days / (1 hours); uint256 constant CHANGE_POINT = 79; uint256 public normalRatePerPercent = (FP48 * 15) / hoursPerYear / CHANGE_POINT / 100; uint256 public highRatePerPercent = (FP48 * (194 - 15)) / hoursPerYear / (100 - CHANGE_POINT) / 100; struct YieldAccumulator { uint256 accumulatorFP; uint256 lastUpdated; uint256 hourlyYieldFP; } struct LendingMetadata { uint256 totalLending; uint256 totalBorrowed; uint256 lendingCap; } mapping(address => LendingMetadata) public lendingMeta; /// @dev accumulate interest per issuer (like compound indices) mapping(address => YieldAccumulator) public borrowYieldAccumulators; /// @dev simple formula for calculating interest relative to accumulator function applyInterest( uint256 balance, uint256 accumulatorFP, uint256 yieldQuotientFP ) internal pure returns (uint256) { // 1 * FP / FP = 1 return (balance * accumulatorFP) / yieldQuotientFP; } function currentLendingRateFP(uint256 totalLending, uint256 totalBorrowing) internal view returns (uint256 rate) { rate = FP48; uint256 utilizationPercent = (100 * totalBorrowing) / totalLending; if (utilizationPercent < CHANGE_POINT) { rate += utilizationPercent * normalRatePerPercent; } else { rate += CHANGE_POINT * normalRatePerPercent + (utilizationPercent - CHANGE_POINT) * highRatePerPercent; } } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } /// @dev maximum function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a; } else { return b; } } /// Available tokens to this issuance function issuanceBalance(address issuance) internal view virtual returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "../libraries/UniswapStyleLib.sol"; abstract contract BaseRouter { modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "Trade has expired"); _; } // **** SWAP **** /// @dev requires the initial amount to have already been sent to the first pair /// and for pairs to be vetted (which getAmountsIn / getAmountsOut do) function _swap( uint256[] memory amounts, address[] memory pairs, address[] memory tokens, address _to ) internal { for (uint256 i; i < pairs.length; i++) { (address input, address output) = (tokens[i], tokens[i + 1]); (address token0, ) = UniswapStyleLib.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < pairs.length - 1 ? pairs[i + 1] : _to; IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]); pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./PriceAware.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course struct CrossMarginAccount { uint256 lastDepositBlock; address[] borrowTokens; // borrowed token address => amount mapping(address => uint256) borrowed; // borrowed token => yield quotient mapping(address => uint256) borrowedYieldQuotientsFP; address[] holdingTokens; // token held in portfolio => amount mapping(address => uint256) holdings; // boolean value of whether an account holds a token mapping(address => bool) holdsToken; } abstract contract CrossMarginAccounts is RoleAware, PriceAware { /// @dev gets used in calculating how much accounts can borrow uint256 public leveragePercent = 300; /// @dev percentage of assets held per assets borrowed at which to liquidate uint256 public liquidationThresholdPercent = 115; /// @dev record of all cross margin accounts mapping(address => CrossMarginAccount) internal marginAccounts; /// @dev total token caps mapping(address => uint256) public tokenCaps; /// @dev tracks total of short positions per token mapping(address => uint256) public totalShort; /// @dev tracks total of long positions per token mapping(address => uint256) public totalLong; uint256 public coolingOffPeriod = 10; /// @dev add an asset to be held by account function addHolding( CrossMarginAccount storage account, address token, uint256 depositAmount ) internal { if (!hasHoldingToken(account, token)) { account.holdingTokens.push(token); account.holdsToken[token] = true; } account.holdings[token] += depositAmount; } /// @dev adjust account to reflect borrowing of token amount function borrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { if (!hasBorrowedToken(account, borrowToken)) { account.borrowTokens.push(borrowToken); account.borrowedYieldQuotientsFP[borrowToken] = Lending(lending()) .getUpdatedBorrowYieldAccuFP(borrowToken); account.borrowed[borrowToken] = borrowAmount; } else { (uint256 oldBorrowed, uint256 accumulatorFP) = Lending(lending()).applyBorrowInterest( account.borrowed[borrowToken], borrowToken, account.borrowedYieldQuotientsFP[borrowToken] ); account.borrowedYieldQuotientsFP[borrowToken] = accumulatorFP; account.borrowed[borrowToken] = oldBorrowed + borrowAmount; } require(positiveBalance(account), "Insufficient balance"); } /// @dev checks whether account is in the black, deposit + earnings relative to borrowed function positiveBalance(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following condition should hold: // holdings / loan >= leveragePercent / (leveragePercent - 100) // => return holdings * (leveragePercent - 100) >= loan * leveragePercent; } /// @dev internal function adjusting holding and borrow balances when debt extinguished function extinguishDebt( CrossMarginAccount storage account, address debtToken, uint256 extinguishAmount ) internal { // will throw if insufficient funds (uint256 borrowAmount, uint256 newYieldQuot) = Lending(lending()).applyBorrowInterest( account.borrowed[debtToken], debtToken, account.borrowedYieldQuotientsFP[debtToken] ); uint256 newBorrowAmount = borrowAmount - extinguishAmount; account.borrowed[debtToken] = newBorrowAmount; if (newBorrowAmount > 0) { account.borrowedYieldQuotientsFP[debtToken] = newYieldQuot; } else { delete account.borrowedYieldQuotientsFP[debtToken]; bool decrement = false; uint256 len = account.borrowTokens.length; for (uint256 i; len > i; i++) { address currToken = account.borrowTokens[i]; if (currToken == debtToken) { decrement = true; } else if (decrement) { account.borrowTokens[i - 1] = currToken; } } account.borrowTokens.pop(); } } /// @dev checks whether an account holds a token function hasHoldingToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.holdsToken[token]; } /// @dev checks whether an account has borrowed a token function hasBorrowedToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.borrowedYieldQuotientsFP[token] > 0; } /// @dev calculate total loan in reference currency, including compound interest function loanInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function holdingsInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPeg(account.holdingTokens, account.holdings); } /// @dev check whether an account can/should be liquidated function belowMaintenanceThreshold(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following should hold: // holdings / loan >= 1.1 // => holdings >= loan * 1.1 return 100 * holdings < liquidationThresholdPercent * loan; } /// @dev go through list of tokens and their amounts, summing up function sumTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.getCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and their amounts, summing up function viewTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.viewCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and ammounts, summing up with interest function sumTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += yieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev go through list of tokens and ammounts, summing up with interest function viewTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += viewYieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev calculate yield for token amount and convert to reference currency function yieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.getCurrentPriceInPeg(token, amountInToken); } /// @dev calculate yield for token amount and convert to reference currency function viewYieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.viewCurrentPriceInPeg(token, amountInToken); } /// @dev move tokens from one holding to another function adjustAmounts( CrossMarginAccount storage account, address fromToken, address toToken, uint256 soldAmount, uint256 boughtAmount ) internal { account.holdings[fromToken] = account.holdings[fromToken] - soldAmount; addHolding(account, toToken, boughtAmount); } /// sets borrow and holding to zero function deleteAccount(CrossMarginAccount storage account) internal { uint256 len = account.borrowTokens.length; for (uint256 borrowIdx; len > borrowIdx; borrowIdx++) { address borrowToken = account.borrowTokens[borrowIdx]; totalShort[borrowToken] -= account.borrowed[borrowToken]; account.borrowed[borrowToken] = 0; account.borrowedYieldQuotientsFP[borrowToken] = 0; } len = account.holdingTokens.length; for (uint256 holdingIdx; len > holdingIdx; holdingIdx++) { address holdingToken = account.holdingTokens[holdingIdx]; totalLong[holdingToken] -= account.holdings[holdingToken]; account.holdings[holdingToken] = 0; account.holdsToken[holdingToken] = false; } delete account.borrowTokens; delete account.holdingTokens; } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./CrossMarginAccounts.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @title Handles liquidation of accounts below maintenance threshold @notice Liquidation can be called by the authorized staker, as determined in the Admin contract. If the authorized staker is delinquent, other participants can jump in and attack, taking their fees and potentially even their stake, depending how delinquent the responsible authorized staker is. */ abstract contract CrossMarginLiquidation is CrossMarginAccounts { event LiquidationShortfall(uint256 amount); event AccountLiquidated(address account); struct Liquidation { uint256 buy; uint256 sell; uint256 blockNum; } /// record kept around until a stake attacker can claim their reward struct AccountLiqRecord { uint256 blockNum; address loser; uint256 amount; address stakeAttacker; } mapping(address => Liquidation) liquidationAmounts; address[] internal liquidationTokens; address[] internal tradersToLiquidate; mapping(address => uint256) public maintenanceFailures; mapping(address => AccountLiqRecord) public stakeAttackRecords; uint256 public avgLiquidationPerCall = 10; uint256 public liqStakeAttackWindow = 5; uint256 public MAINTAINER_CUT_PERCENT = 5; uint256 public failureThreshold = 10; /// Set failure threshold function setFailureThreshold(uint256 threshFactor) external onlyOwnerExec { failureThreshold = threshFactor; } /// Set liquidity stake attack window function setLiqStakeAttackWindow(uint256 window) external onlyOwnerExec { liqStakeAttackWindow = window; } /// Set maintainer's percent cut function setMaintainerCutPercent(uint256 cut) external onlyOwnerExec { MAINTAINER_CUT_PERCENT = cut; } /// @dev calcLiquidationAmounts does a number of tasks in this contract /// and some of them are not straightforward. /// First of all it aggregates liquidation amounts, /// as well as which traders are ripe for liquidation, in storage (not in memory) /// owing to the fact that arrays can't be pushed to and hash maps don't /// exist in memory. /// Then it also returns any stake attack funds if the stake was unsuccessful /// (i.e. current caller is authorized). Also see context below. function calcLiquidationAmounts( address[] memory liquidationCandidates, bool isAuthorized ) internal returns (uint256 attackReturns) { liquidationTokens = new address[](0); tradersToLiquidate = new address[](0); for ( uint256 traderIndex = 0; liquidationCandidates.length > traderIndex; traderIndex++ ) { address traderAddress = liquidationCandidates[traderIndex]; CrossMarginAccount storage account = marginAccounts[traderAddress]; if (belowMaintenanceThreshold(account)) { tradersToLiquidate.push(traderAddress); uint256 len = account.holdingTokens.length; for (uint256 sellIdx = 0; len > sellIdx; sellIdx++) { address token = account.holdingTokens[sellIdx]; Liquidation storage liquidation = liquidationAmounts[token]; if (liquidation.blockNum != block.number) { liquidation.sell = account.holdings[token]; liquidation.buy = 0; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.sell += account.holdings[token]; } } len = account.borrowTokens.length; for (uint256 buyIdx = 0; len > buyIdx; buyIdx++) { address token = account.borrowTokens[buyIdx]; Liquidation storage liquidation = liquidationAmounts[token]; (uint256 loanAmount, ) = Lending(lending()).applyBorrowInterest( account.borrowed[token], token, account.borrowedYieldQuotientsFP[token] ); Lending(lending()).payOff(token, loanAmount); if (liquidation.blockNum != block.number) { liquidation.sell = 0; liquidation.buy = loanAmount; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.buy += loanAmount; } } } AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; if (isAuthorized) { attackReturns += _disburseLiqAttack(liqAttackRecord); } } } function _disburseLiqAttack(AccountLiqRecord storage liqAttackRecord) internal returns (uint256 returnAmount) { if (liqAttackRecord.amount > 0) { // validate attack records, if any uint256 blockDiff = min( block.number - liqAttackRecord.blockNum, liqStakeAttackWindow ); uint256 attackerCut = (liqAttackRecord.amount * blockDiff) / liqStakeAttackWindow; Fund(fund()).withdraw( PriceAware.peg, liqAttackRecord.stakeAttacker, attackerCut ); Admin a = Admin(admin()); uint256 penalty = (a.maintenanceStakePerBlock() * attackerCut) / avgLiquidationPerCall; a.penalizeMaintenanceStake( liqAttackRecord.loser, penalty, liqAttackRecord.stakeAttacker ); // return remainder, after cut was taken to authorized stakekr returnAmount = liqAttackRecord.amount - attackerCut; } } /// Disburse liquidity stake attacks function disburseLiqStakeAttacks(address[] memory liquidatedAccounts) external { for (uint256 i = 0; liquidatedAccounts.length > i; i++) { address liqAccount = liquidatedAccounts[i]; AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[liqAccount]; if ( block.number > liqAttackRecord.blockNum + liqStakeAttackWindow ) { _disburseLiqAttack(liqAttackRecord); delete stakeAttackRecords[liqAccount]; } } } function liquidateFromPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIdx = 0; len > tokenIdx; tokenIdx++) { address buyToken = liquidationTokens[tokenIdx]; Liquidation storage liq = liquidationAmounts[buyToken]; if (liq.buy > liq.sell) { pegAmount += PriceAware.liquidateFromPeg( buyToken, liq.buy - liq.sell ); delete liquidationAmounts[buyToken]; } } } function liquidateToPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIndex = 0; len > tokenIndex; tokenIndex++) { address token = liquidationTokens[tokenIndex]; Liquidation storage liq = liquidationAmounts[token]; if (liq.sell > liq.buy) { uint256 sellAmount = liq.sell - liq.buy; pegAmount += PriceAware.liquidateToPeg(token, sellAmount); delete liquidationAmounts[token]; } } } function maintainerIsFailing() internal view returns (bool) { (address currentMaintainer, ) = Admin(admin()).viewCurrentMaintenanceStaker(); return maintenanceFailures[currentMaintainer] > failureThreshold * avgLiquidationPerCall; } /// called by maintenance stakers to liquidate accounts below liquidation threshold function liquidate(address[] memory liquidationCandidates) external noIntermediary returns (uint256 maintainerCut) { bool isAuthorized = Admin(admin()).isAuthorizedStaker(msg.sender); bool canTakeNow = isAuthorized || maintainerIsFailing(); // calcLiquidationAmounts does a lot of the work here // * aggregates both sell and buy side targets to be liquidated // * returns attacker cuts to them // * aggregates any returned fees from unauthorized (attacking) attempts maintainerCut = calcLiquidationAmounts( liquidationCandidates, isAuthorized ); uint256 sale2pegAmount = liquidateToPeg(); uint256 peg2targetCost = liquidateFromPeg(); delete liquidationTokens; // this may be a bit imprecise, since individual shortfalls may be obscured // by overall returns and the maintainer cut is taken out of the net total, // but it gives us the general picture uint256 costWithCut = (peg2targetCost * (100 + MAINTAINER_CUT_PERCENT)) / 100; if (costWithCut > sale2pegAmount) { emit LiquidationShortfall(costWithCut - sale2pegAmount); canTakeNow = canTakeNow && IERC20(peg).balanceOf(fund()) > costWithCut; } address loser = address(0); if (!canTakeNow) { // whoever is the current responsible maintenance staker // and liable to lose their stake loser = Admin(admin()).getUpdatedCurrentStaker(); } // iterate over traders and send back their money // as well as giving attackers their due, in case caller isn't authorized for ( uint256 traderIdx = 0; tradersToLiquidate.length > traderIdx; traderIdx++ ) { address traderAddress = tradersToLiquidate[traderIdx]; CrossMarginAccount storage account = marginAccounts[traderAddress]; uint256 holdingsValue = holdingsInPeg(account); uint256 borrowValue = loanInPeg(account); // 5% of value borrowed uint256 maintainerCut4Account = (borrowValue * MAINTAINER_CUT_PERCENT) / 100; maintainerCut += maintainerCut4Account; if (!canTakeNow) { // This could theoretically lead to a previous attackers // record being overwritten, but only if the trader restarts // their account and goes back into the red within the short time window // which would be a costly attack requiring collusion without upside AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; liqAttackRecord.amount = maintainerCut4Account; liqAttackRecord.stakeAttacker = msg.sender; liqAttackRecord.blockNum = block.number; liqAttackRecord.loser = loser; } // send back trader money // include 1% for protocol uint256 forfeited = maintainerCut4Account + (borrowValue * 101) / 100; if (holdingsValue > forfeited) { // send remaining funds back to trader Fund(fund()).withdraw( PriceAware.peg, traderAddress, holdingsValue - forfeited ); } emit AccountLiquidated(traderAddress); deleteAccount(account); } avgLiquidationPerCall = (avgLiquidationPerCall * 99 + maintainerCut) / 100; if (canTakeNow) { Fund(fund()).withdraw(PriceAware.peg, msg.sender, maintainerCut); } address currentMaintainer = Admin(admin()).getUpdatedCurrentStaker(); if (isAuthorized) { if (maintenanceFailures[currentMaintainer] > maintainerCut) { maintenanceFailures[currentMaintainer] -= maintainerCut; } else { maintenanceFailures[currentMaintainer] = 0; } } else { maintenanceFailures[currentMaintainer] += maintainerCut; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./CrossMarginLiquidation.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course contract CrossMarginTrading is CrossMarginLiquidation, IMarginTrading { constructor(address _peg, address _roles) RoleAware(_roles) PriceAware(_peg) {} /// @dev admin function to set the token cap function setTokenCap(address token, uint256 cap) external onlyOwnerExecActivator { tokenCaps[token] = cap; } /// @dev setter for cooling off period for withdrawing funds after deposit function setCoolingOffPeriod(uint256 blocks) external onlyOwnerExec { coolingOffPeriod = blocks; } /// @dev admin function to set leverage function setLeveragePercent(uint256 _leveragePercent) external onlyOwnerExec { leveragePercent = _leveragePercent; } /// @dev admin function to set liquidation threshold function setLiquidationThresholdPercent(uint256 threshold) external onlyOwnerExec { liquidationThresholdPercent = threshold; } /// @dev gets called by router to affirm a deposit to an account function registerDeposit( address trader, address token, uint256 depositAmount ) external override returns (uint256 extinguishableDebt) { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; account.lastDepositBlock = block.number; if (account.borrowed[token] > 0) { extinguishableDebt = min(depositAmount, account.borrowed[token]); extinguishDebt(account, token, extinguishableDebt); totalShort[token] -= extinguishableDebt; } // no overflow because depositAmount >= extinguishableDebt uint256 addedHolding = depositAmount - extinguishableDebt; _registerDeposit(account, token, addedHolding); } function _registerDeposit( CrossMarginAccount storage account, address token, uint256 addedHolding ) internal { addHolding(account, token, addedHolding); totalLong[token] += addedHolding; require( tokenCaps[token] >= totalLong[token], "Exceeds global token cap" ); } /// @dev gets called by router to affirm borrowing event function registerBorrow( address trader, address borrowToken, uint256 borrowAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; addHolding(account, borrowToken, borrowAmount); _registerBorrow(account, borrowToken, borrowAmount); } function _registerBorrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { totalShort[borrowToken] += borrowAmount; totalLong[borrowToken] += borrowAmount; require( tokenCaps[borrowToken] >= totalShort[borrowToken] && tokenCaps[borrowToken] >= totalLong[borrowToken], "Exceeds global token cap" ); borrow(account, borrowToken, borrowAmount); } /// @dev gets called by router to affirm withdrawal of tokens from account function registerWithdrawal( address trader, address withdrawToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerWithdrawal(account, withdrawToken, withdrawAmount); } function _registerWithdrawal( CrossMarginAccount storage account, address withdrawToken, uint256 withdrawAmount ) internal { require( block.number > account.lastDepositBlock + coolingOffPeriod, "No withdrawal soon after deposit" ); totalLong[withdrawToken] -= withdrawAmount; // throws on underflow account.holdings[withdrawToken] = account.holdings[withdrawToken] - withdrawAmount; require(positiveBalance(account), "Insufficient balance"); } /// @dev overcollateralized borrowing on a cross margin account, called by router function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerDeposit(account, depositToken, depositAmount); _registerBorrow(account, borrowToken, withdrawAmount); _registerWithdrawal(account, borrowToken, withdrawAmount); account.lastDepositBlock = block.number; } /// @dev gets called by router to register a trade and borrow and extinguish as necessary function registerTradeAndBorrow( address trader, address tokenFrom, address tokenTo, uint256 inAmount, uint256 outAmount ) external override returns (uint256 extinguishableDebt, uint256 borrowAmount) { require(isMarginTrader(msg.sender), "Calling contr. not an authorized"); CrossMarginAccount storage account = marginAccounts[trader]; if (account.borrowed[tokenTo] > 0) { extinguishableDebt = min(outAmount, account.borrowed[tokenTo]); extinguishDebt(account, tokenTo, extinguishableDebt); totalShort[tokenTo] -= extinguishableDebt; } uint256 sellAmount = inAmount; uint256 fromHoldings = account.holdings[tokenFrom]; if (inAmount > fromHoldings) { sellAmount = fromHoldings; /// won't overflow borrowAmount = inAmount - sellAmount; } if (inAmount > borrowAmount) { totalLong[tokenFrom] -= inAmount - borrowAmount; } if (outAmount > extinguishableDebt) { totalLong[tokenTo] += outAmount - extinguishableDebt; } require( tokenCaps[tokenTo] >= totalLong[tokenTo], "Exceeds global token cap" ); adjustAmounts( account, tokenFrom, tokenTo, sellAmount, outAmount - extinguishableDebt ); if (borrowAmount > 0) { totalShort[tokenFrom] += borrowAmount; require( tokenCaps[tokenFrom] >= totalShort[tokenFrom], "Exceeds global token cap" ); borrow(account, tokenFrom, borrowAmount); } } /// @dev can get called by router to register the dissolution of an account function registerLiquidation(address trader) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; require(loanInPeg(account) == 0, "Can't liquidate: borrowing"); deleteAccount(account); } /// @dev currently holding in this token function viewBalanceInToken(address trader, address token) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return account.holdings[token]; } /// @dev view function to display account held assets state function getHoldingAmounts(address trader) external view override returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ) { CrossMarginAccount storage account = marginAccounts[trader]; holdingTokens = account.holdingTokens; holdingAmounts = new uint256[](account.holdingTokens.length); for (uint256 idx = 0; holdingTokens.length > idx; idx++) { address tokenAddress = holdingTokens[idx]; holdingAmounts[idx] = account.holdings[tokenAddress]; } } /// @dev view function to display account borrowing state function getBorrowAmounts(address trader) external view override returns (address[] memory borrowTokens, uint256[] memory borrowAmounts) { CrossMarginAccount storage account = marginAccounts[trader]; borrowTokens = account.borrowTokens; borrowAmounts = new uint256[](account.borrowTokens.length); for (uint256 idx = 0; borrowTokens.length > idx; idx++) { address tokenAddress = borrowTokens[idx]; borrowAmounts[idx] = Lending(lending()).viewWithBorrowInterest( account.borrowed[tokenAddress], tokenAddress, account.borrowedYieldQuotientsFP[tokenAddress] ); } } /// @dev view function to get loan amount in peg function viewLoanInPeg(address trader) external view returns (uint256 amount) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function viewHoldingsInPeg(address trader) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPeg(account.holdingTokens, account.holdings); } /// @dev can this trader be liquidated? function canBeLiquidated(address trader) external view returns (bool) { CrossMarginAccount storage account = marginAccounts[trader]; uint256 loan = viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); uint256 holdings = viewTokensInPeg(account.holdingTokens, account.holdings); return liquidationThresholdPercent * loan >= 100 * holdings; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWETH.sol"; import "./RoleAware.sol"; /// @title Manage funding contract Fund is RoleAware { using SafeERC20 for IERC20; /// wrapped ether address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /// Deposit an active token function deposit(address depositToken, uint256 depositAmount) external { IERC20(depositToken).safeTransferFrom( msg.sender, address(this), depositAmount ); } /// Deposit token on behalf of `sender` function depositFor( address sender, address depositToken, uint256 depositAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized deposit"); IERC20(depositToken).safeTransferFrom( sender, address(this), depositAmount ); } /// Deposit to wrapped ether function depositToWETH() external payable { IWETH(WETH).deposit{value: msg.value}(); } // withdrawers role function withdraw( address withdrawalToken, address recipient, uint256 withdrawalAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount); } // withdrawers role function withdrawETH(address recipient, uint256 withdrawalAmount) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IWETH(WETH).withdraw(withdrawalAmount); Address.sendValue(payable(recipient), withdrawalAmount); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./BaseLending.sol"; struct HourlyBond { uint256 amount; uint256 yieldQuotientFP; uint256 moduloHour; } /// @title Here we offer subscriptions to auto-renewing hourly bonds /// Funds are locked in for an 50 minutes per hour, while interest rates float abstract contract HourlyBondSubscriptionLending is BaseLending { mapping(address => YieldAccumulator) hourlyBondYieldAccumulators; uint256 constant RATE_UPDATE_WINDOW = 10 minutes; uint256 public withdrawalWindow = 20 minutes; uint256 constant MAX_HOUR_UPDATE = 4; // issuer => holder => bond record mapping(address => mapping(address => HourlyBond)) public hourlyBondAccounts; uint256 public borrowingFactorPercent = 200; uint256 constant borrowMinAPR = 6; uint256 constant borrowMinHourlyYield = FP48 + (borrowMinAPR * FP48) / 100 / hoursPerYear; function _makeHourlyBond( address issuer, address holder, uint256 amount ) internal { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; updateHourlyBondAmount(issuer, bond); YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; bond.yieldQuotientFP = yieldAccumulator.accumulatorFP; if (bond.amount == 0) { bond.moduloHour = block.timestamp % (1 hours); } bond.amount += amount; lendingMeta[issuer].totalLending += amount; } function updateHourlyBondAmount(address issuer, HourlyBond storage bond) internal { uint256 yieldQuotientFP = bond.yieldQuotientFP; if (yieldQuotientFP > 0) { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); uint256 oldAmount = bond.amount; bond.amount = applyInterest( bond.amount, yA.accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = bond.amount - oldAmount; lendingMeta[issuer].totalLending += deltaAmount; } } // Retrieves bond balance for issuer and holder function viewHourlyBondAmount(address issuer, address holder) public view returns (uint256) { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; uint256 yieldQuotientFP = bond.yieldQuotientFP; uint256 cumulativeYield = viewCumulativeYieldFP( hourlyBondYieldAccumulators[issuer], block.timestamp ); if (yieldQuotientFP > 0) { return applyInterest(bond.amount, cumulativeYield, yieldQuotientFP); } else { return bond.amount; } } function _withdrawHourlyBond( address issuer, HourlyBond storage bond, uint256 amount ) internal { // how far the current hour has advanced (relative to acccount hourly clock) uint256 currentOffset = (block.timestamp - bond.moduloHour) % (1 hours); require( withdrawalWindow >= currentOffset, "Tried withdrawing outside subscription cancellation time window" ); bond.amount -= amount; lendingMeta[issuer].totalLending -= amount; } function calcCumulativeYieldFP( YieldAccumulator storage yieldAccumulator, uint256 timeDelta ) internal view returns (uint256 accumulatorFP) { uint256 secondsDelta = timeDelta % (1 hours); // linearly interpolate interest for seconds // FP * FP * 1 / (FP * 1) = FP accumulatorFP = yieldAccumulator.accumulatorFP + (yieldAccumulator.accumulatorFP * (yieldAccumulator.hourlyYieldFP - FP48) * secondsDelta) / (FP48 * 1 hours); uint256 hoursDelta = timeDelta / (1 hours); if (hoursDelta > 0) { uint256 accumulatorBeforeFP = accumulatorFP; for (uint256 i = 0; hoursDelta > i && MAX_HOUR_UPDATE > i; i++) { // FP48 * FP48 / FP48 = FP48 accumulatorFP = (accumulatorFP * yieldAccumulator.hourlyYieldFP) / FP48; } // a lot of time has passed if (hoursDelta > MAX_HOUR_UPDATE) { // apply interest in non-compounding way accumulatorFP += ((accumulatorFP - accumulatorBeforeFP) * (hoursDelta - MAX_HOUR_UPDATE)) / MAX_HOUR_UPDATE; } } } /// @dev updates yield accumulators for both borrowing and lending /// issuer address represents a token function updateHourlyYield(address issuer) public returns (uint256 hourlyYield) { return getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ) .hourlyYieldFP; } /// @dev updates yield accumulators for both borrowing and lending function getUpdatedHourlyYield( address issuer, YieldAccumulator storage accumulator, uint256 window ) internal returns (YieldAccumulator storage) { uint256 lastUpdated = accumulator.lastUpdated; uint256 timeDelta = (block.timestamp - lastUpdated); if (timeDelta > window) { YieldAccumulator storage borrowAccumulator = borrowYieldAccumulators[issuer]; accumulator.accumulatorFP = calcCumulativeYieldFP( accumulator, timeDelta ); LendingMetadata storage meta = lendingMeta[issuer]; accumulator.hourlyYieldFP = currentLendingRateFP( meta.totalLending, meta.totalBorrowed ); accumulator.lastUpdated = block.timestamp; updateBorrowYieldAccu(borrowAccumulator); borrowAccumulator.hourlyYieldFP = max( borrowMinHourlyYield, FP48 + (borrowingFactorPercent * (accumulator.hourlyYieldFP - FP48)) / 100 ); } return accumulator; } function updateBorrowYieldAccu(YieldAccumulator storage borrowAccumulator) internal { uint256 timeDelta = block.timestamp - borrowAccumulator.lastUpdated; if (timeDelta > RATE_UPDATE_WINDOW) { borrowAccumulator.accumulatorFP = calcCumulativeYieldFP( borrowAccumulator, timeDelta ); borrowAccumulator.lastUpdated = block.timestamp; } } function getUpdatedBorrowYieldAccuFP(address issuer) external returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); return yA.accumulatorFP; } function viewCumulativeYieldFP( YieldAccumulator storage yA, uint256 timestamp ) internal view returns (uint256) { uint256 timeDelta = (timestamp - yA.lastUpdated); if (timeDelta > RATE_UPDATE_WINDOW) { return calcCumulativeYieldFP(yA, timeDelta); } else { return yA.accumulatorFP; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "./HourlyBondSubscriptionLending.sol"; import "../libraries/IncentiveReporter.sol"; // TODO activate bonds for lending /// @title Manage lending for a variety of bond issuers contract Lending is RoleAware, HourlyBondSubscriptionLending { /// mapping issuers to tokens /// (in crossmargin, the issuers are tokens themselves) mapping(address => address) public issuerTokens; /// In case of shortfall, adjust debt mapping(address => uint256) public haircuts; /// map of available issuers mapping(address => bool) public activeIssuers; uint256 constant BORROW_RATE_UPDATE_WINDOW = 60 minutes; constructor(address _roles) RoleAware(_roles) {} /// Make a issuer available for protocol function activateIssuer(address issuer) external { activateIssuer(issuer, issuer); } /// Make issuer != token available for protocol (isol. margin) function activateIssuer(address issuer, address token) public onlyOwnerExecActivator { activeIssuers[issuer] = true; issuerTokens[issuer] = token; } /// Remove a issuer from trading availability function deactivateIssuer(address issuer) external onlyOwnerExecActivator { activeIssuers[issuer] = false; } /// Set lending cap function setLendingCap(address issuer, uint256 cap) external onlyOwnerExecActivator { lendingMeta[issuer].lendingCap = cap; } /// Set withdrawal window function setWithdrawalWindow(uint256 window) external onlyOwnerExec { withdrawalWindow = window; } function setNormalRatePerPercent(uint256 rate) external onlyOwnerExec { normalRatePerPercent = rate; } function setHighRatePerPercent(uint256 rate) external onlyOwnerExec { highRatePerPercent = rate; } /// Set hourly yield APR for issuer function setHourlyYieldAPR(address issuer, uint256 aprPercent) external onlyOwnerExecActivator { YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; if (yieldAccumulator.accumulatorFP == 0) { uint256 yieldFP = FP48 + (FP48 * aprPercent) / 100 / (24 * 365); hourlyBondYieldAccumulators[issuer] = YieldAccumulator({ accumulatorFP: FP48, lastUpdated: block.timestamp, hourlyYieldFP: yieldFP }); } else { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, yieldAccumulator, RATE_UPDATE_WINDOW ); yA.hourlyYieldFP = (FP48 * (100 + aprPercent)) / 100 / (24 * 365); } } /// @dev how much interest has accrued to a borrowed balance over time function applyBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external returns (uint256 balanceWithInterest, uint256 accumulatorFP) { require(isBorrower(msg.sender), "Not approved call"); YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); accumulatorFP = yA.accumulatorFP; balanceWithInterest = applyInterest( balance, accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = balanceWithInterest - balance; LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += deltaAmount; } /// @dev view function to get balance with borrowing interest applied function viewWithBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external view returns (uint256) { uint256 accumulatorFP = viewCumulativeYieldFP( borrowYieldAccumulators[issuer], block.timestamp ); return applyInterest(balance, accumulatorFP, yieldQuotientFP); } /// @dev gets called by router to register if a trader borrows issuers function registerBorrow(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], BORROW_RATE_UPDATE_WINDOW ); require( meta.totalLending >= meta.totalBorrowed, "Insufficient lending" ); } /// @dev gets called when external sources provide lending function registerLend(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called when external sources pay withdraw their bobnd function registerWithdrawal(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending -= amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called by router if loan is extinguished function payOff(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); lendingMeta[issuer].totalBorrowed -= amount; } /// @dev get the borrow yield for a specific issuer/token function viewAccumulatedBorrowingYieldFP(address issuer) external view returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; return viewCumulativeYieldFP(yA, block.timestamp); } function viewAPRPer10k(YieldAccumulator storage yA) internal view returns (uint256) { uint256 hourlyYieldFP = yA.hourlyYieldFP; uint256 aprFP = ((hourlyYieldFP * 10_000 - FP48 * 10_000) * 365 days) / (1 hours); return aprFP / FP48; } /// @dev get current borrowing interest per 10k for a token / issuer function viewBorrowAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(borrowYieldAccumulators[issuer]); } /// @dev get current lending APR per 10k for a token / issuer function viewHourlyBondAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(hourlyBondYieldAccumulators[issuer]); } /// @dev In a liquidity crunch make a fallback bond until liquidity is good again function makeFallbackBond( address issuer, address holder, uint256 amount ) external { require(isLender(msg.sender), "Not an approved lender"); _makeHourlyBond(issuer, holder, amount); } /// @dev withdraw an hour bond function withdrawHourlyBond(address issuer, uint256 amount) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); super._withdrawHourlyBond(issuer, bond, amount); if (bond.amount == 0) { delete hourlyBondAccounts[issuer][msg.sender]; } disburse(issuer, msg.sender, amount); IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// Shut down hourly bond account for `issuer` function closeHourlyBondAccount(address issuer) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); uint256 amount = bond.amount; super._withdrawHourlyBond(issuer, bond, amount); disburse(issuer, msg.sender, amount); delete hourlyBondAccounts[issuer][msg.sender]; IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// @dev buy hourly bond subscription function buyHourlyBondSubscription(address issuer, uint256 amount) external { require(activeIssuers[issuer], "Not approved issuer"); collectToken(issuer, msg.sender, amount); super._makeHourlyBond(issuer, msg.sender, amount); IncentiveReporter.addToClaimAmount(issuer, msg.sender, amount); } function initBorrowYieldAccumulator(address issuer) external onlyOwnerExecActivator { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; require(yA.accumulatorFP == 0, "don't re-initialize"); yA.accumulatorFP = FP48; yA.lastUpdated = block.timestamp; yA.hourlyYieldFP = FP48 + (FP48 * borrowMinAPR) / 100 / (365 * 24); } function setBorrowingFactorPercent(uint256 borrowingFactor) external onlyOwnerExec { borrowingFactorPercent = borrowingFactor; } function issuanceBalance(address issuer) internal view override returns (uint256) { address token = issuerTokens[issuer]; if (token == issuer) { // cross margin return IERC20(token).balanceOf(fund()); } else { return lendingMeta[issuer].totalLending - haircuts[issuer]; } } function disburse( address issuer, address recipient, uint256 amount ) internal { uint256 haircutAmount = haircuts[issuer]; if (haircutAmount > 0 && amount > 0) { uint256 totalLending = lendingMeta[issuer].totalLending; uint256 adjustment = (amount * min(totalLending, haircutAmount)) / totalLending; amount = amount - adjustment; haircuts[issuer] -= adjustment; } address token = issuerTokens[issuer]; Fund(fund()).withdraw(token, recipient, amount); } function collectToken( address issuer, address source, uint256 amount ) internal { Fund(fund()).depositFor(source, issuer, amount); } function haircut(uint256 amount) external { haircuts[msg.sender] += amount; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "../interfaces/IMarginTrading.sol"; import "./Lending.sol"; import "./Admin.sol"; import "./BaseRouter.sol"; import "../libraries/IncentiveReporter.sol"; /// @title Top level transaction controller contract MarginRouter is RoleAware, BaseRouter { event AccountUpdated(address indexed trader); uint256 public constant mswapFeesPer10k = 10; address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /////////////////////////// // Cross margin endpoints /////////////////////////// /// @notice traders call this to deposit funds on cross margin function crossDeposit(address depositToken, uint256 depositAmount) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, depositToken, depositAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(depositToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( depositToken, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice deposit wrapped ehtereum into cross margin account function crossDepositETH() external payable { Fund(fund()).depositToWETH{value: msg.value}(); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, WETH, msg.value ); if (extinguishAmount > 0) { Lending(lending()).payOff(WETH, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( WETH, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice withdraw deposits/earnings from cross margin account function crossWithdraw(address withdrawToken, uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, withdrawToken, withdrawAmount ); Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice withdraw ethereum from cross margin account function crossWithdrawETH(uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, WETH, withdrawAmount ); Fund(fund()).withdrawETH(msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice borrow into cross margin trading account function crossBorrow(address borrowToken, uint256 borrowAmount) external { Lending(lending()).registerBorrow(borrowToken, borrowAmount); IMarginTrading(crossMarginTrading()).registerBorrow( msg.sender, borrowToken, borrowAmount ); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, borrowAmount ); emit AccountUpdated(msg.sender); } /// @notice convenience function to perform overcollateralized borrowing /// against a cross margin account. /// @dev caution: the account still has to have a positive balaance at the end /// of the withdraw. So an underwater account may not be able to withdraw function crossOvercollateralizedBorrow( address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); Lending(lending()).registerBorrow(borrowToken, withdrawAmount); IMarginTrading(crossMarginTrading()).registerOvercollateralizedBorrow( msg.sender, depositToken, depositAmount, borrowToken, withdrawAmount ); Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, withdrawAmount ); emit AccountUpdated(msg.sender); } /// @notice close an account that is no longer borrowing and return gains function crossCloseAccount() external { (address[] memory holdingTokens, uint256[] memory holdingAmounts) = IMarginTrading(crossMarginTrading()).getHoldingAmounts(msg.sender); // requires all debts paid off IMarginTrading(crossMarginTrading()).registerLiquidation(msg.sender); for (uint256 i; holdingTokens.length > i; i++) { Fund(fund()).withdraw( holdingTokens[i], msg.sender, holdingAmounts[i] ); } emit AccountUpdated(msg.sender); } /// @notice entry point for swapping tokens held in cross margin account function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { // calc fees uint256 fees = takeFeesFromInput(amountIn); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn - fees, amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amountIn, amounts[amounts.length - 1] ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } /// @notice entry point for swapping tokens held in cross margin account function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut + takeFeesFromOutput(amountOut), amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amounts[0], amountOut ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } /// @dev helper function does all the work of telling other contracts /// about a cross margin trade function registerTrade( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) internal { (uint256 extinguishAmount, uint256 borrowAmount) = IMarginTrading(crossMarginTrading()).registerTradeAndBorrow( trader, inToken, outToken, inAmount, outAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(outToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( outToken, trader, extinguishAmount ); } if (borrowAmount > 0) { Lending(lending()).registerBorrow(inToken, borrowAmount); IncentiveReporter.addToClaimAmount(inToken, trader, borrowAmount); } emit AccountUpdated(trader); } ///////////// // Helpers ///////////// /// @dev internal helper swapping exact token for token on AMM function _fundSwapExactT4T( uint256[] memory amounts, uint256 amountOutMin, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[amounts.length - 1] >= amountOutMin, "MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } /// @notice make swaps on AMM using protocol funds, only for authorized contracts function authorizedSwapExactT4T( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn, amms, tokens ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } // @dev internal helper swapping exact token for token on on AMM function _fundSwapT4ExactT( uint256[] memory amounts, uint256 amountInMax, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[0] <= amountInMax, "MarginRouter: EXCESSIVE_INPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } //// @notice swap protocol funds on AMM, only for authorized function authorizedSwapT4ExactT( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } function takeFeesFromOutput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / 10_000; } function takeFeesFromInput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k); } function getAmountsOut( uint256 inAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens); } function getAmountsIn( uint256 outAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "./MarginRouter.sol"; import "../libraries/UniswapStyleLib.sol"; /// Stores how many of token you could get for 1k of peg struct TokenPrice { uint256 lastUpdated; uint256 priceFP; address[] liquidationTokens; bytes32 amms; address[] inverseLiquidationTokens; bytes32 inverseAmms; } struct VolatilitySetting { uint256 priceUpdateWindow; uint256 updateRatePermil; uint256 voluntaryUpdateWindow; } struct PairPrice { uint256 cumulative; uint256 lastUpdated; uint256 priceFP; } /// @title The protocol features several mechanisms to prevent vulnerability to /// price manipulation: /// 1) global exposure caps on all tokens which need to be raised gradually /// during the process of introducing a new token, making attacks unprofitable /// due to lack of scale /// 2) Exponential moving average with cautious price update. Prices for estimating /// how much a trader can borrow need not be extremely current and precise, mainly /// they must be resilient against extreme manipulation /// 3) Liquidators may not call from a contract address, to prevent extreme forms of /// of front-running and other price manipulation. abstract contract PriceAware is RoleAware { uint256 constant FP112 = 2**112; address public immutable peg; mapping(address => TokenPrice) public tokenPrices; mapping(address => mapping(address => PairPrice)) public pairPrices; /// update window in blocks // TODO uint256 public priceUpdateWindow = 20 minutes; uint256 public voluntaryUpdateWindow = 5 minutes; uint256 public UPDATE_RATE_PERMIL = 400; VolatilitySetting[] public volatilitySettings; constructor(address _peg) { peg = _peg; } /// Set window for price updates function setPriceUpdateWindow(uint16 window, uint256 voluntaryWindow) external onlyOwnerExec { priceUpdateWindow = window; voluntaryUpdateWindow = voluntaryWindow; } /// Add a new volatility setting function addVolatilitySetting( uint256 _priceUpdateWindow, uint256 _updateRatePermil, uint256 _voluntaryUpdateWindow ) external onlyOwnerExec { volatilitySettings.push( VolatilitySetting({ priceUpdateWindow: _priceUpdateWindow, updateRatePermil: _updateRatePermil, voluntaryUpdateWindow: _voluntaryUpdateWindow }) ); } /// Choose a volatitlity setting function chooseVolatilitySetting(uint256 index) external onlyOwnerExecDisabler { VolatilitySetting storage vs = volatilitySettings[index]; if (vs.updateRatePermil > 0) { UPDATE_RATE_PERMIL = vs.updateRatePermil; priceUpdateWindow = vs.priceUpdateWindow; voluntaryUpdateWindow = vs.voluntaryUpdateWindow; } } /// Set rate for updates function setUpdateRate(uint256 rate) external onlyOwnerExec { UPDATE_RATE_PERMIL = rate; } function getCurrentPriceInPeg(address token, uint256 inAmount) internal returns (uint256) { return getCurrentPriceInPeg(token, inAmount, false); } function getCurrentPriceInPeg( address token, uint256 inAmount, bool voluntary ) public returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 timeDelta = block.timestamp - tokenPrice.lastUpdated; if ( timeDelta > priceUpdateWindow || tokenPrice.priceFP == 0 || (voluntary && timeDelta > voluntaryUpdateWindow) ) { // update the currently cached price uint256 priceUpdateFP; priceUpdateFP = getPriceByPairs( tokenPrice.liquidationTokens, tokenPrice.amms ); _setPriceVal(tokenPrice, priceUpdateFP, UPDATE_RATE_PERMIL); } priceInPeg = (inAmount * tokenPrice.priceFP) / FP112; } } /// Get view of current price of token in peg function viewCurrentPriceInPeg(address token, uint256 inAmount) public view returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 priceFP = tokenPrice.priceFP; priceInPeg = (inAmount * priceFP) / FP112; } } function _setPriceVal( TokenPrice storage tokenPrice, uint256 updateFP, uint256 weightPerMil ) internal { tokenPrice.priceFP = (tokenPrice.priceFP * (1000 - weightPerMil) + updateFP * weightPerMil) / 1000; tokenPrice.lastUpdated = block.timestamp; } /// add path from token to current liquidation peg function setLiquidationPath(bytes32 amms, address[] memory tokens) external onlyOwnerExecActivator { address token = tokens[0]; if (token != peg) { TokenPrice storage tokenPrice = tokenPrices[token]; tokenPrice.amms = amms; tokenPrice.liquidationTokens = tokens; tokenPrice.inverseLiquidationTokens = new address[](tokens.length); bytes32 inverseAmms; for (uint256 i = 0; tokens.length - 1 > i; i++) { initPairPrice(tokens[i], tokens[i + 1], amms[i]); bytes32 shifted = bytes32(amms[i]) >> ((tokens.length - 2 - i) * 8); inverseAmms = inverseAmms | shifted; } tokenPrice.inverseAmms = inverseAmms; for (uint256 i = 0; tokens.length > i; i++) { tokenPrice.inverseLiquidationTokens[i] = tokens[ tokens.length - i - 1 ]; } tokenPrice.priceFP = getPriceByPairs(tokens, amms); tokenPrice.lastUpdated = block.timestamp; } } function liquidateToPeg(address token, uint256 amount) internal returns (uint256) { if (token == peg) { return amount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapExactT4T( amount, 0, tP.amms, tP.liquidationTokens ); uint256 outAmount = amounts[amounts.length - 1]; return outAmount; } } function liquidateFromPeg(address token, uint256 targetAmount) internal returns (uint256) { if (token == peg) { return targetAmount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapT4ExactT( targetAmount, type(uint256).max, tP.amms, tP.inverseLiquidationTokens ); return amounts[0]; } } function getPriceByPairs(address[] memory tokens, bytes32 amms) internal returns (uint256 priceFP) { priceFP = FP112; for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; (, , uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); uint256 timeDelta = pairLastUpdated - pairPrice.lastUpdated; if (timeDelta > voluntaryUpdateWindow) { // we are in business (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); uint256 cumulative = inToken == token0 ? IUniswapV2Pair(pair).price0CumulativeLast() : IUniswapV2Pair(pair).price1CumulativeLast(); uint256 pairPriceFP = (cumulative - pairPrice.cumulative) / timeDelta; priceFP = (priceFP * pairPriceFP) / FP112; pairPrice.priceFP = pairPriceFP; pairPrice.cumulative = cumulative; pairPrice.lastUpdated = pairLastUpdated; } else { priceFP = (priceFP * pairPrice.priceFP) / FP112; } } } function initPairPrice( address inToken, address outToken, bytes1 amm ) internal { address pair = amm == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; if (pairPrice.lastUpdated == 0) { (uint112 reserve0, uint112 reserve1, uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); if (inToken == token0) { pairPrice.priceFP = (FP112 * reserve1) / reserve0; pairPrice.cumulative = IUniswapV2Pair(pair) .price0CumulativeLast(); } else { pairPrice.priceFP = (FP112 * reserve0) / reserve1; pairPrice.cumulative = IUniswapV2Pair(pair) .price1CumulativeLast(); } pairPrice.lastUpdated = block.timestamp; pairPrice.lastUpdated = pairLastUpdated; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Roles.sol"; /// @title Role management behavior /// Main characters are for service discovery /// Whereas roles are for access control contract RoleAware { Roles public immutable roles; mapping(uint256 => address) public mainCharacterCache; mapping(address => mapping(uint256 => bool)) public roleCache; constructor(address _roles) { require(_roles != address(0), "Please provide valid roles address"); roles = Roles(_roles); } modifier noIntermediary() { require( msg.sender == tx.origin, "Currently no intermediaries allowed for this function call" ); _; } // @dev Throws if called by any account other than the owner or executor modifier onlyOwnerExec() { require( owner() == msg.sender || executor() == msg.sender, "Roles: caller is not the owner" ); _; } modifier onlyOwnerExecDisabler() { require( owner() == msg.sender || executor() == msg.sender || disabler() == msg.sender, "Caller is not the owner, executor or authorized disabler" ); _; } modifier onlyOwnerExecActivator() { require( owner() == msg.sender || executor() == msg.sender || isTokenActivator(msg.sender), "Caller is not the owner, executor or authorized activator" ); _; } function updateRoleCache(uint256 role, address contr) public virtual { roleCache[contr][role] = roles.getRole(role, contr); } function updateMainCharacterCache(uint256 role) public virtual { mainCharacterCache[role] = roles.mainCharacters(role); } function owner() internal view returns (address) { return roles.owner(); } function executor() internal returns (address) { return roles.executor(); } function disabler() internal view returns (address) { return mainCharacterCache[DISABLER]; } function fund() internal view returns (address) { return mainCharacterCache[FUND]; } function lending() internal view returns (address) { return mainCharacterCache[LENDING]; } function marginRouter() internal view returns (address) { return mainCharacterCache[MARGIN_ROUTER]; } function crossMarginTrading() internal view returns (address) { return mainCharacterCache[CROSS_MARGIN_TRADING]; } function feeController() internal view returns (address) { return mainCharacterCache[FEE_CONTROLLER]; } function price() internal view returns (address) { return mainCharacterCache[PRICE_CONTROLLER]; } function admin() internal view returns (address) { return mainCharacterCache[ADMIN]; } function incentiveDistributor() internal view returns (address) { return mainCharacterCache[INCENTIVE_DISTRIBUTION]; } function tokenAdmin() internal view returns (address) { return mainCharacterCache[TOKEN_ADMIN]; } function isBorrower(address contr) internal view returns (bool) { return roleCache[contr][BORROWER]; } function isFundTransferer(address contr) internal view returns (bool) { return roleCache[contr][FUND_TRANSFERER]; } function isMarginTrader(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_TRADER]; } function isFeeSource(address contr) internal view returns (bool) { return roleCache[contr][FEE_SOURCE]; } function isMarginCaller(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_CALLER]; } function isLiquidator(address contr) internal view returns (bool) { return roleCache[contr][LIQUIDATOR]; } function isAuthorizedFundTrader(address contr) internal view returns (bool) { return roleCache[contr][AUTHORIZED_FUND_TRADER]; } function isIncentiveReporter(address contr) internal view returns (bool) { return roleCache[contr][INCENTIVE_REPORTER]; } function isTokenActivator(address contr) internal view returns (bool) { return roleCache[contr][TOKEN_ACTIVATOR]; } function isStakePenalizer(address contr) internal view returns (bool) { return roleCache[contr][STAKE_PENALIZER]; } function isLender(address contr) internal view returns (bool) { return roleCache[contr][LENDER]; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IDependencyController.sol"; // we chose not to go with an enum // to make this list easy to extend uint256 constant FUND_TRANSFERER = 1; uint256 constant MARGIN_CALLER = 2; uint256 constant BORROWER = 3; uint256 constant MARGIN_TRADER = 4; uint256 constant FEE_SOURCE = 5; uint256 constant LIQUIDATOR = 6; uint256 constant AUTHORIZED_FUND_TRADER = 7; uint256 constant INCENTIVE_REPORTER = 8; uint256 constant TOKEN_ACTIVATOR = 9; uint256 constant STAKE_PENALIZER = 10; uint256 constant LENDER = 11; uint256 constant FUND = 101; uint256 constant LENDING = 102; uint256 constant MARGIN_ROUTER = 103; uint256 constant CROSS_MARGIN_TRADING = 104; uint256 constant FEE_CONTROLLER = 105; uint256 constant PRICE_CONTROLLER = 106; uint256 constant ADMIN = 107; uint256 constant INCENTIVE_DISTRIBUTION = 108; uint256 constant TOKEN_ADMIN = 109; uint256 constant DISABLER = 1001; uint256 constant DEPENDENCY_CONTROLLER = 1002; /// @title Manage permissions of contracts and ownership of everything /// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during /// beta and will then be transfered to governance /// https://github.com/marginswap/governance contract Roles is Ownable { mapping(address => mapping(uint256 => bool)) public roles; mapping(uint256 => address) public mainCharacters; constructor() Ownable() { // token activation from the get-go roles[msg.sender][TOKEN_ACTIVATOR] = true; } /// @dev Throws if called by any account other than the owner. modifier onlyOwnerExecDepController() { require( owner() == msg.sender || executor() == msg.sender || mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender, "Roles: caller is not the owner" ); _; } function giveRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = true; } function removeRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = false; } function setMainCharacter(uint256 role, address actor) external onlyOwnerExecDepController { mainCharacters[role] = actor; } function getRole(uint256 role, address contr) external view returns (bool) { return roles[contr][role]; } /// @dev current executor function executor() public returns (address exec) { address depController = mainCharacters[DEPENDENCY_CONTROLLER]; if (depController != address(0)) { exec = IDependencyController(depController).currentExecutor(); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IDependencyController { function currentExecutor() external returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IMarginTrading { function registerDeposit( address trader, address token, uint256 amount ) external returns (uint256 extinguishAmount); function registerWithdrawal( address trader, address token, uint256 amount ) external; function registerBorrow( address trader, address token, uint256 amount ) external; function registerTradeAndBorrow( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) external returns (uint256 extinguishAmount, uint256 borrowAmount); function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external; function registerLiquidation(address trader) external; function getHoldingAmounts(address trader) external view returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ); function getBorrowAmounts(address trader) external view returns (address[] memory borrowTokens, uint256[] memory borrowAmounts); } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } library IncentiveReporter { event AddToClaim(address topic, address indexed claimant, uint256 amount); event SubtractFromClaim( address topic, address indexed claimant, uint256 amount ); /// Start / increase amount of claim function addToClaimAmount( address topic, address recipient, uint256 claimAmount ) internal { emit AddToClaim(topic, recipient, claimAmount); } /// Decrease amount of claim function subtractFromClaimAmount( address topic, address recipient, uint256 subtractAmount ) internal { emit SubtractFromClaim(topic, recipient, subtractAmount); } } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; library UniswapStyleLib { address constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Identical address!"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Zero address!"); } // fetches and sorts the reserves for a pair function getReserves( address pair, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1_000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1_000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( uint256 amountIn, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[0] = amountIn; pairs = new address[](tokens.length - 1); for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( uint256 amountOut, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[amounts.length - 1] = amountOut; pairs = new address[](tokens.length - 1); for (uint256 i = tokens.length - 1; i > 0; i--) { address inToken = tokens[i - 1]; address outToken = tokens[i]; address pair = amms[i - 1] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i - 1] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } // calculates the CREATE2 address for a pair without making any external calls function pairForUni(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", UNISWAP_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } function pairForSushi(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", SUSHI_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } }
@notice entry point for swapping tokens held in cross margin account checks that trader is within allowed lending bounds
function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut + takeFeesFromOutput(amountOut), amms, tokens ); registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amounts[0], amountOut ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); }
563,891
[ 1, 4099, 1634, 364, 7720, 1382, 2430, 15770, 316, 6828, 7333, 2236, 4271, 716, 1284, 765, 353, 3470, 2935, 328, 2846, 4972, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7720, 5157, 1290, 14332, 5157, 12, 203, 3639, 2254, 5034, 3844, 1182, 16, 203, 3639, 2254, 5034, 3844, 382, 2747, 16, 203, 3639, 1731, 1578, 2125, 959, 16, 203, 3639, 1758, 8526, 745, 892, 2430, 16, 203, 3639, 2254, 5034, 14096, 203, 565, 262, 3903, 3387, 12, 22097, 1369, 13, 1135, 261, 11890, 5034, 8526, 3778, 30980, 13, 288, 203, 3639, 1758, 8526, 3778, 5574, 31, 203, 3639, 261, 8949, 87, 16, 5574, 13, 273, 1351, 291, 91, 438, 2885, 5664, 18, 588, 6275, 87, 382, 12, 203, 5411, 3844, 1182, 397, 4862, 2954, 281, 1265, 1447, 12, 8949, 1182, 3631, 203, 5411, 2125, 959, 16, 203, 5411, 2430, 203, 3639, 11272, 203, 203, 3639, 1744, 22583, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 2430, 63, 20, 6487, 203, 5411, 2430, 63, 7860, 18, 2469, 300, 404, 6487, 203, 5411, 30980, 63, 20, 6487, 203, 5411, 3844, 1182, 203, 3639, 11272, 203, 203, 3639, 389, 74, 1074, 12521, 56, 24, 14332, 56, 12, 8949, 87, 16, 3844, 382, 2747, 16, 5574, 16, 2430, 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 ]
pragma solidity 0.5.16; import "./IETHFlashBorrower.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.3.0/contracts/math/SafeMath.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.3.0/contracts/utils/ReentrancyGuard.sol"; // @notice Any contract that inherits this contract becomes a flash lender of any/all ETH that it holds // @dev DO NOT USE. This is has not been audited. contract ETHFlashLender is ReentrancyGuard { using SafeMath for uint256; // should never be changed by inheriting contracts uint256 private _ethBorrowerDebt; // internal vars -- okay for inheriting contracts to change uint256 internal _ethBorrowFee; // e.g.: 0.003e18 means 0.3% fee uint256 constant internal ONE = 1e18; // @notice Borrow ETH via a flash loan. See ETHFlashBorrower for example. // @audit Necessarily violates checks-effects-interactions pattern. // @audit The `nonReentrant` modifier is critical here. function ETHFlashLoan(uint256 amount) external nonReentrant { // record debt _ethBorrowerDebt = amount.mul(ONE.add(_ethBorrowFee)).div(ONE); // send borrower the tokens msg.sender.transfer(amount); // hand over control to borrower IETHFlashBorrower(msg.sender).executeOnETHFlashLoan(amount, _ethBorrowerDebt); // check that debt was fully repaid require(_ethBorrowerDebt == 0, "loan not paid back"); } // @notice Repay all or part of the loan function repayEthDebt() public payable { _ethBorrowerDebt = _ethBorrowerDebt.sub(msg.value); // does not allow overpayment } function ethBorrowerDebt() public view returns (uint256) { return _ethBorrowerDebt; } function ethBorrowFee() public view returns (uint256) { return _ethBorrowFee; } }
@notice Any contract that inherits this contract becomes a flash lender of any/all ETH that it holds @dev DO NOT USE. This is has not been audited. should never be changed by inheriting contracts internal vars -- okay for inheriting contracts to change @notice Borrow ETH via a flash loan. See ETHFlashBorrower for example. @audit Necessarily violates checks-effects-interactions pattern. @audit The `nonReentrant` modifier is critical here.
contract ETHFlashLender is ReentrancyGuard { using SafeMath for uint256; uint256 private _ethBorrowerDebt; uint256 constant internal ONE = 1e18; function ETHFlashLoan(uint256 amount) external nonReentrant { _ethBorrowerDebt = amount.mul(ONE.add(_ethBorrowFee)).div(ONE); msg.sender.transfer(amount); IETHFlashBorrower(msg.sender).executeOnETHFlashLoan(amount, _ethBorrowerDebt); require(_ethBorrowerDebt == 0, "loan not paid back"); } function repayEthDebt() public payable { } function ethBorrowerDebt() public view returns (uint256) { return _ethBorrowerDebt; } function ethBorrowFee() public view returns (uint256) { return _ethBorrowFee; } }
12,653,565
[ 1, 2961, 6835, 716, 24664, 333, 6835, 12724, 279, 9563, 328, 2345, 434, 1281, 19, 454, 512, 2455, 716, 518, 14798, 225, 5467, 4269, 14988, 18, 1220, 353, 711, 486, 2118, 8215, 329, 18, 1410, 5903, 506, 3550, 635, 6811, 310, 20092, 2713, 4153, 1493, 21194, 364, 6811, 310, 20092, 358, 2549, 225, 605, 15318, 512, 2455, 3970, 279, 9563, 28183, 18, 2164, 512, 2455, 11353, 38, 15318, 264, 364, 3454, 18, 632, 17413, 423, 21513, 12471, 815, 4271, 17, 13867, 87, 17, 2761, 4905, 1936, 18, 632, 17413, 1021, 1375, 5836, 426, 8230, 970, 68, 9606, 353, 11239, 2674, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 512, 2455, 11353, 48, 2345, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 3238, 389, 546, 38, 15318, 264, 758, 23602, 31, 203, 203, 203, 565, 2254, 5034, 5381, 2713, 15623, 273, 404, 73, 2643, 31, 203, 203, 565, 445, 512, 2455, 11353, 1504, 304, 12, 11890, 5034, 3844, 13, 3903, 1661, 426, 8230, 970, 288, 203, 203, 3639, 389, 546, 38, 15318, 264, 758, 23602, 273, 3844, 18, 16411, 12, 5998, 18, 1289, 24899, 546, 38, 15318, 14667, 13, 2934, 2892, 12, 5998, 1769, 203, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 8949, 1769, 203, 203, 3639, 467, 1584, 44, 11353, 38, 15318, 264, 12, 3576, 18, 15330, 2934, 8837, 1398, 1584, 44, 11353, 1504, 304, 12, 8949, 16, 389, 546, 38, 15318, 264, 758, 23602, 1769, 203, 203, 3639, 2583, 24899, 546, 38, 15318, 264, 758, 23602, 422, 374, 16, 315, 383, 304, 486, 30591, 1473, 8863, 203, 565, 289, 203, 203, 565, 445, 2071, 528, 41, 451, 758, 23602, 1435, 1071, 8843, 429, 288, 203, 565, 289, 203, 203, 203, 565, 445, 13750, 38, 15318, 264, 758, 23602, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 546, 38, 15318, 264, 758, 23602, 31, 203, 565, 289, 203, 377, 203, 565, 445, 13750, 38, 15318, 14667, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 546, 38, 15318, 14667, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100 ]
pragma solidity ^0.4.19; // Wolf Crypto pooling contract for Quant Network Overledger // written by @iamdefinitelyahuman 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 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; } } contract ERC20 { function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} } contract PresalePool { // SafeMath is a library to ensure that math operations do not have overflow errors // https://zeppelin-solidity.readthedocs.io/en/latest/safemath.html using SafeMath for uint; // The contract has 3 stages: // 1 - The initial state. Contributors can deposit or withdraw eth to the contract. // 2 - The owner has closed the contract for further deposits. Contributing addresses can still withdraw eth from the contract. // 3 - The eth is sent from the contract to the receiver. Unused eth can be claimed by contributors immediately. // Once tokens are sent to the contract, the owner enables withdrawals and contributors can withdraw their tokens. uint8 public contractStage = 1; // These variables are set at the time of contract creation // the address that creates the contract address public owner; // the minimum eth amount (in wei) that can be sent by a contributing address uint constant public contributionMin = 100000000000000000; // the maximum eth amount (in wei) that can be held by the contract uint public maxContractBalance; // the % of tokens kept by the contract owner uint public feePct; // the address that the pool will be paid out to address public receiverAddress; // These variables are all initially blank and are set at some point during the contract // the amount of eth (in wei) present in the contract when it was submitted uint public finalBalance; // an array containing eth amounts to be refunded in stage 3 uint[] public ethRefundAmount; // the default token contract to be used for withdrawing tokens in stage 3 address public activeToken; // a data structure for holding the contribution amount, eth refund status, and token withdrawal status for each address struct Contributor { uint ethRefund; uint balance; mapping (address => uint) tokensClaimed; } // a mapping that holds the contributor struct for each address mapping (address => Contributor) contributorMap; // a data structure for holding information related to token withdrawals. struct TokenAllocation { ERC20 token; uint[] pct; uint balanceRemaining; } // a mapping that holds the token allocation struct for each token address mapping (address => TokenAllocation) distributionMap; // this modifier is used for functions that can only be accessed by the contract creator modifier onlyOwner () { require (msg.sender == owner); _; } // this modifier is used to prevent re-entrancy exploits during contract > contract interaction bool locked; modifier noReentrancy() { require (!locked); locked = true; _; locked = false; } // Events triggered throughout contract execution // These can be watched via geth filters to keep up-to-date with the contract event ContributorBalanceChanged (address contributor, uint totalBalance); event PoolSubmitted (address receiver, uint amount); event WithdrawalsOpen (address tokenAddr); event TokensWithdrawn (address receiver, uint amount); event EthRefundReceived (address sender, uint amount); event EthRefunded (address receiver, uint amount); event ERC223Received (address token, uint value); // These are internal functions used for calculating fees, eth and token allocations as % // returns a value as a % accurate to 20 decimal points function _toPct (uint numerator, uint denominator ) internal pure returns (uint) { return numerator.mul(10 ** 20) / denominator; } // returns % of any number, where % given was generated with toPct function _applyPct (uint numerator, uint pct) internal pure returns (uint) { return numerator.mul(pct) / (10 ** 20); } // This function is called at the time of contract creation, // it sets the initial variables and the contract owner. function PresalePool(address receiverAddr, uint contractMaxInWei, uint fee) public { require (fee < 100); require (receiverAddr != 0x00); owner = msg.sender; receiverAddress = receiverAddr; maxContractBalance = contractMaxInWei; feePct = _toPct(fee,100); } // This function is called whenever eth is sent into the contract. // The amount sent is added to the balance in the Contributor struct associated with the sending address. function () payable public { if (contractStage == 1) { _ethDeposit(); } else if (contractStage == 3) { _ethRefund(); } else revert(); } // Internal function for handling eth deposits during contract stage one. function _ethDeposit () internal { assert (contractStage == 1); uint size; address addr = msg.sender; assembly { size := extcodesize(addr) } require (size == 0); require (this.balance <= maxContractBalance); var c = contributorMap[msg.sender]; uint newBalance = c.balance.add(msg.value); require (newBalance >= contributionMin); c.balance = newBalance; ContributorBalanceChanged(msg.sender, newBalance); } // Internal function for handling eth refunds during stage three. function _ethRefund () internal { assert (contractStage == 3); require (msg.sender == owner || msg.sender == receiverAddress); require (msg.value >= contributionMin); ethRefundAmount.push(msg.value); EthRefundReceived(msg.sender, msg.value); } // This function is called to withdraw eth or tokens from the contract. It can only be called by addresses that show a balance greater than 0. // If called during stages one or two, the full eth balance deposited into the contract is returned and the contributor's balance reset to 0. // If called during stage three, the contributor's unused eth will be returned, as well as any available tokens. // The token address may be provided optionally to withdraw tokens that are not currently the default token (airdrops). function withdraw (address tokenAddr) public { var c = contributorMap[msg.sender]; require (c.balance > 0); if (contractStage < 3) { uint amountToTransfer = c.balance; c.balance = 0; msg.sender.transfer(amountToTransfer); ContributorBalanceChanged(msg.sender, 0); } else { _withdraw(msg.sender, tokenAddr); } } // This function allows the contract owner to force a withdrawal to any contributor. function withdrawFor (address contributor, address tokenAddr) public onlyOwner { require (contractStage == 3); require (contributorMap[contributor].balance > 0); _withdraw(contributor, tokenAddr); } // This internal function handles withdrawals during stage three. // The associated events will fire to notify when a refund or token allocation is claimed. function _withdraw (address receiver, address tokenAddr) internal { assert (contractStage == 3); var c = contributorMap[receiver]; if (tokenAddr == 0x00) { tokenAddr = activeToken; } var d = distributionMap[tokenAddr]; require ( ethRefundAmount.length > c.ethRefund || d.pct.length > c.tokensClaimed[tokenAddr] ); if (ethRefundAmount.length > c.ethRefund) { uint pct = _toPct(c.balance, finalBalance); uint ethAmount = 0; for (uint i = c.ethRefund; i < ethRefundAmount.length; i++) { ethAmount = ethAmount.add(_applyPct(ethRefundAmount[i], pct)); } c.ethRefund = ethRefundAmount.length; if (ethAmount > 0) { receiver.transfer(ethAmount); EthRefunded(receiver, ethAmount); } } if (d.pct.length > c.tokensClaimed[tokenAddr]) { uint tokenAmount = 0; for (i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) { tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i])); } c.tokensClaimed[tokenAddr] = d.pct.length; if (tokenAmount > 0) { require (d.token.transfer(receiver, tokenAmount)); d.balanceRemaining = d.balanceRemaining.sub(tokenAmount); TokensWithdrawn(receiver, tokenAmount); } } } // This function can be called during stages one or two to modify the maximum balance of the contract. // It can only be called by the owner. The amount cannot be set to lower than the current balance of the contract. function modifyMaxContractBalance (uint amount) public onlyOwner { require (contractStage < 3); require (amount >= contributionMin); require (amount >= this.balance); maxContractBalance = amount; } // This callable function returns the total pool cap, current balance and remaining balance to be filled. function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) { if (contractStage == 1) { remaining = maxContractBalance.sub(this.balance); } else { remaining = 0; } return (maxContractBalance,this.balance,remaining); } // This callable function returns the balance, contribution cap, and remaining available balance of any contributor. function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) { var c = contributorMap[addr]; if (contractStage == 1) { remaining = maxContractBalance.sub(this.balance); } else { remaining = 0; } return (c.balance, maxContractBalance, remaining); } // This callable function returns the token balance that a contributor can currently claim. function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) { var c = contributorMap[addr]; var d = distributionMap[tokenAddr]; for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) { tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i])); } return tokenAmount; } // This function closes further contributions to the contract, advancing it to stage two. // It can only be called by the owner. After this call has been made, contributing addresses // can still remove their eth from the contract but cannot contribute any more. function closeContributions () public onlyOwner { require (contractStage == 1); contractStage = 2; } // This function reopens the contract to contributions, returning it to stage one. // It can only be called by the owner during stage two. function reopenContributions () public onlyOwner { require (contractStage == 2); contractStage = 1; } // This function sends the pooled eth to the receiving address, calculates the % of unused eth to be returned, // and advances the contract to stage three. It can only be called by the contract owner during stages one or two. // The amount to send (given in wei) must be specified during the call. As this function can only be executed once, // it is VERY IMPORTANT not to get the amount wrong. function submitPool (uint amountInWei) public onlyOwner noReentrancy { require (contractStage < 3); require (contributionMin <= amountInWei && amountInWei <= this.balance); finalBalance = this.balance; require (receiverAddress.call.value(amountInWei).gas(msg.gas.sub(5000))()); if (this.balance > 0) ethRefundAmount.push(this.balance); contractStage = 3; PoolSubmitted(receiverAddress, amountInWei); } // This function opens the contract up for token withdrawals. // It can only be called by the owner during stage 3. The owner specifies the address of an ERC20 token // contract that this contract has a balance in, and optionally a bool to prevent this token from being // the default withdrawal (in the event of an airdrop, for example). function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy { require (contractStage == 3); if (notDefault) { require (activeToken != 0x00); } else { activeToken = tokenAddr; } var d = distributionMap[tokenAddr]; if (d.pct.length == 0) d.token = ERC20(tokenAddr); uint amount = d.token.balanceOf(this).sub(d.balanceRemaining); require (amount > 0); if (feePct > 0) { require (d.token.transfer(owner,_applyPct(amount, feePct))); } amount = d.token.balanceOf(this).sub(d.balanceRemaining); d.balanceRemaining = d.token.balanceOf(this); d.pct.push(_toPct(amount, finalBalance)); WithdrawalsOpen(tokenAddr); } // This is a standard function required for ERC223 compatibility. function tokenFallback (address from, uint value, bytes data) public { ERC223Received(from, value); } }
This function is called at the time of contract creation, it sets the initial variables and the contract owner.
function PresalePool(address receiverAddr, uint contractMaxInWei, uint fee) public { require (fee < 100); require (receiverAddr != 0x00); owner = msg.sender; receiverAddress = receiverAddr; maxContractBalance = contractMaxInWei; feePct = _toPct(fee,100); }
1,181,240
[ 1, 2503, 445, 353, 2566, 622, 326, 813, 434, 6835, 6710, 16, 518, 1678, 326, 2172, 3152, 471, 326, 6835, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 225, 445, 18346, 5349, 2864, 12, 2867, 5971, 3178, 16, 2254, 6835, 2747, 382, 3218, 77, 16, 2254, 14036, 13, 1071, 288, 203, 565, 2583, 261, 21386, 411, 2130, 1769, 203, 565, 2583, 261, 24454, 3178, 480, 374, 92, 713, 1769, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 565, 5971, 1887, 273, 5971, 3178, 31, 203, 565, 943, 8924, 13937, 273, 6835, 2747, 382, 3218, 77, 31, 203, 565, 14036, 52, 299, 273, 389, 30329, 299, 12, 21386, 16, 6625, 1769, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// // MIT License // // Copyright (c) 2018 REGA Risk Sharing // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Author: Sergei Sevriugin // Version: 0.0.1 // pragma solidity ^0.4.17; import './TokenContainer.sol'; /// TokenPool is TokenContainer with 4 level pool structure: /// Super Pool (Level 0), Pool (Level 1), Sub Pool (Level 2) and Token (Level 3) /// Level Container / Member /// ------------------------------------------------ /// 0 SuperPool /// 1 |______Pool /// 2 |______SubPool /// 3 |_______Token contract TokenPool is TokenContainer { /// TokenPool insertPool event /// @param id inserted token ID /// @param poolId pool ID /// @param level pool level event InsertPool(uint256 id, uint256 poolId, uint8 level); /// TokenPool value distribution event /// @param id NFT token ID for value distribution /// @param superPoolValue SuperPool Share /// @param poolValue Pool Share /// @param subPoolValue SubPool Share /// @param comission Comission = the rest after all pools event DistributeValue(uint256 id, uint256 superPoolValue, uint256 poolValue, uint256 subPoolValue, uint256 comission); /// TokenPool Second Tier Call event /// @param id NFT token ID that emits event /// @param value 2nd tier capital call value event SecondTierCall(uint256 id, uint256 value); /// TokenPool ShortOfFunds event /// @param id NFT token ID that emits event /// @param poolId pool ID that can't pay /// @param value that pool can't pay /// @param level pool level that can't event ShortOfFunds(uint256 id, uint256 poolId, uint256 value, uint8 level); /// TokenPool Payment Value event /// @param id NFT token ID that emits event /// @param value paid value /// @param level pool level that paid event PaymentValue(uint256 id, uint256 value, uint8 level); /// @dev Pool defines pool structure /// @param level Pool level: 0,1,2,3 /// @param maxNumber Maximum number of pools on this lavel /// @param maxMember Maximum number of members for the pool /// @param number Pool number for this level /// @param last NFT ID for last availible pool (with member capacity) struct Pool { uint8 level; // Pool level: 0,1,2,3 uint256 maxNumber; // Maximum number of pools on this lavel uint256 maxMember; // Maximum number of members for the pool uint256 number; // Pool number for this level uint256 last; // NFT ID for last availible pool (with member capacity) uint256 share; // Pool share from token investment } /// @dev Pool structure Pool[] pools; // Pool structure /// inset new member in the pool /// @param _id NFT token ID to inserr /// @param _level Pool level to insert /// @return TRUE if insert is done function _getParent(uint256 _id, uint8 _level) internal view returns (uint256 parentId) { // by default returns pools[_level].last but must be overloaded to use score to calculate right pool _id; parentId = pools[_level].last; } function _getCapacity(uint256 _id, uint8 _level) internal view returns (uint256 parentId) { // by default returns pools[_level].maxMember - 1; but can be overloaded to use score to calculate right pool capacity _id; parentId = pools[_level].maxMember - 1; } function _insertPool(uint256 _id, uint8 _level) internal returns (bool) { uint256 parentId = _getParent(_id, _level); // pool NFT token ID uint256 size = _getPoolSize(parentId); // current pool size uint256 max = _getCapacity(_id, _level); // max pool size - 1 // check if there is a place to insert if (size < max) { // simple insert addToken(_id, parentId); // add to pool InsertPool(_id, parentId, _level); // event return true; } else { // no capacity in the current pool, so, need to add new pool // check if it's possible if(pools[_level].number == pools[_level].maxNumber) { // no capacity to add new pool at this lavel return false; } else { // make a copy from the last pool uint newPool = _createNFT(uint256(0), nfts[parentId].metadata, nfts[parentId].kind, owner); if (newPool != uint(0)) { // insert pool in the pool structure if (_insertPool(newPool, _level-1)) { // insert token to the new pool addToken(_id, newPool); // add to pool InsertPool(_id, newPool, _level); // event // record new pool data in the structure pools[_level].last = newPool; // new pool is last one pools[_level].number++; // new pool and member are inserted return true; } else { return false; } } else { return false; } } } } /// distribute value of the token _id to pools /// @dev make it as simmple as possible for fixed pool staructure /// @param _id NFT token ID to distribute value /// @return TRUE if distribution is complited function _distributeValue(uint256 _id) internal returns (bool) { // need to make sure that _id is terminal node in the structure require(_id != uint256(0) && _id < nfts.length); require(nfts[_id].level == maxLevel - 1); // now we can check then the path has all pools uint256 subPoolId = tokenIndexToPoolToken[_id]; require(subPoolId != uint256(0)); // SubPool uint256 poolId = tokenIndexToPoolToken[subPoolId]; require(poolId != uint256(0)); // Pool uint256 superPoolId = tokenIndexToPoolToken[poolId]; require(superPoolId != uint256(0)); // SuperPool // calculate values to distribute based of pool structure shares uint256 subPoolValue = nfts[_id].value * pools[2].share / 100; require(subPoolValue != uint256(0)); uint256 poolValue = nfts[_id].value * pools[1].share / 100; require(poolValue != uint256(0)); uint256 superPoolValue = nfts[_id].value * pools[0].share / 100; require(superPoolValue != uint256(0)); uint256 commission = nfts[_id].value - subPoolValue - poolValue - superPoolValue; require(commission != uint256(0)); // ready to distribute nfts[subPoolId].value = nfts[subPoolId].value + subPoolValue; nfts[poolId].value = nfts[poolId].value + poolValue; nfts[superPoolId].value = nfts[superPoolId].value + superPoolValue; // we will keep comission in the reserved token with ID = 0 nfts[0].value = nfts[0].value + commission; // the distribution is done 0 --> _id value nfts[_id].value = uint256(0); DistributeValue(_id, superPoolValue, poolValue, subPoolValue, commission); return true; } /// insert token in pool structure /// @param _id NFT token ID to insert /// @return TRUE if insert is done function insertPool(uint256 _id) ownerOnly public returns(bool) { require(_id != uint256(0) && _id < nfts.length); // call internal function assert(_insertPool(_id, 2)); // if inserted then make value distribution assert(_distributeValue(_id)); return true; } /// insert token in pool structure /// @param _id NFT token ID to insert /// @return TRUE if insert is done function _addTokenToSubPool(uint256 _id) internal returns(bool) { require(_id != uint256(0) && _id < nfts.length); // call internal function assert(_insertPool(_id, 2)); // if inserted then make value distribution assert(_distributeValue(_id)); return true; } /// get collected comission /// @return commission commission value function getComission() public view returns(uint256 commission) { commission = nfts[0].value; } /// get value distribution except commission /// @return distribution [0] = SuperPool, [1] = Pool, [2] = SubPool and [3] = Tokens (must be 0) function getDistribution() public view returns(uint256[4] distribution) { uint8 _level; distribution[0] = uint256(0); // Super Pool Value distribution[1] = uint256(0); // Pool Value distribution[2] = uint256(0); // SubPool Value distribution[3] = uint256(0); // Tokens Value (must be 0) for (uint256 id = 1; id < nfts.length; id++) { _level = uint8(nfts[id].level); if(_level < maxLevel) { distribution[_level] = distribution[_level] + nfts[id].value; } else { distribution[3] = distribution[3] + nfts[id].value; // if something wrong w/ level add to tokens } } } function _payValue(uint256 _id, uint256 _value) internal returns(uint256[4] distribution) { require(_id != uint256(0) && _id < nfts.length); require(_value != uint256(0)); distribution[0] = uint256(0); // Super Pool Value distribution[1] = uint256(0); // Pool Value distribution[2] = uint256(0); // SubPool Value distribution[3] = uint256(0); // Tokens Value (must be 0) // now we can check then the path has all pools uint256 subPoolId = tokenIndexToPoolToken[_id]; require(subPoolId != uint256(0)); // SubPool uint256 poolId = tokenIndexToPoolToken[subPoolId]; require(poolId != uint256(0)); // Pool uint256 superPoolId = tokenIndexToPoolToken[poolId]; require(superPoolId != uint256(0)); // SuperPool if(_value <= nfts[subPoolId].value) { distribution[2] = _value; nfts[subPoolId].value = nfts[subPoolId].value - distribution[2]; PaymentValue(_id, _value, uint8(2)); } else if (_value <= nfts[poolId].value + nfts[subPoolId].value) { ShortOfFunds(_id, subPoolId, _value, uint8(2)); distribution[2] = nfts[subPoolId].value; distribution[1] = _value - nfts[subPoolId].value; nfts[subPoolId].value = nfts[subPoolId].value - distribution[2]; nfts[poolId].value = nfts[poolId].value - distribution[1]; PaymentValue(_id, _value, uint8(1)); } else if (_value <= nfts[superPoolId].value + nfts[poolId].value + nfts[subPoolId].value) { ShortOfFunds(_id, poolId, _value, uint8(1)); distribution[2] = nfts[subPoolId].value; distribution[1] = nfts[poolId].value; distribution[0] = _value - nfts[subPoolId].value - nfts[poolId].value; nfts[subPoolId].value = nfts[subPoolId].value - distribution[2]; nfts[poolId].value = nfts[poolId].value - distribution[1]; nfts[superPoolId].value = nfts[superPoolId].value - distribution[0]; PaymentValue(_id, _value, uint8(0)); } else { ShortOfFunds(_id, superPoolId, _value, uint8(0)); SecondTierCall(_id, _value); } } function _checkPayment(uint256 _id, uint256 _value) internal view returns(bool possible) { possible = false; uint256 subPoolId = tokenIndexToPoolToken[_id]; require(subPoolId != uint256(0)); // SubPool uint256 poolId = tokenIndexToPoolToken[subPoolId]; require(poolId != uint256(0)); // Pool uint256 superPoolId = tokenIndexToPoolToken[poolId]; require(superPoolId != uint256(0)); // SuperPool if(_value <= nfts[subPoolId].value) { possible = true; } else if (_value <= nfts[poolId].value + nfts[subPoolId].value) { possible = true; } else if (_value <= nfts[superPoolId].value + nfts[poolId].value + nfts[subPoolId].value) { possible = true; } } function checkPaymentAmount(uint256 _id, uint256 _value) public view returns(uint8 level, uint256 amtSubPool, uint256 amtPool, uint256 amtSuperPool, uint256 balance) { level = uint8(4); uint256[4] memory distribution; distribution[0] = uint256(0); // Super Pool Value distribution[1] = uint256(0); // Pool Value distribution[2] = uint256(0); // SubPool Value distribution[3] = uint256(0); // Tokens Value (must be 0) require(_id != uint256(0) && _id < nfts.length); require(_value != uint256(0)); require(_owns(msg.sender, _id)); uint256 subPoolId = tokenIndexToPoolToken[_id]; require(subPoolId != uint256(0)); // SubPool uint256 poolId = tokenIndexToPoolToken[subPoolId]; require(poolId != uint256(0)); // Pool uint256 superPoolId = tokenIndexToPoolToken[poolId]; require(superPoolId != uint256(0)); // SuperPool level = uint8(3); if(_value <= nfts[subPoolId].value) { level = uint8(2); distribution[2] = _value; } else if (_value <= nfts[poolId].value + nfts[subPoolId].value) { level = uint8(1); distribution[2] = nfts[subPoolId].value; distribution[1] = _value - nfts[subPoolId].value; } else if (_value <= nfts[superPoolId].value + nfts[poolId].value + nfts[subPoolId].value) { level = uint8(0); distribution[2] = nfts[subPoolId].value; distribution[1] = nfts[poolId].value; distribution[0] = _value - nfts[subPoolId].value - nfts[poolId].value; } amtSubPool = distribution[2]; amtPool = distribution[1]; amtSuperPool = distribution[0]; balance = address(this).balance; } /// TokenPool Constructor function TokenPool(string _name, string _symbol) TokenContainer(_name, _symbol) public { maxLevel = 4; // FIXED DO NOT CHANGE! // Creating templates uint superPoolId = _createNFT(10 ether, "SuperPool", uint256(1), owner); // fix initial capital for 10 Ether uint poolId = _createNFT(uint256(0), "Pool", uint256(1), owner); uint subPoolId = _createNFT(uint256(0), "SubPool", uint256(2), owner); // Build initil structure SubPool --> Pool --> SuperPool addToken(poolId, superPoolId); addToken(subPoolId, poolId); // Build configuration // SuperPool configuration Pool memory superPool = Pool({ level: uint8(0), maxNumber: uint256(1), maxMember: uint256(10), number: uint256(1), last: uint256(superPoolId), share: uint256(10) }); pools.push(superPool); // Pool configuration Pool memory pool = Pool({ level: uint8(1), maxNumber: uint256(10), maxMember: uint256(100), number: uint256(1), last: uint256(poolId), share: uint256(20) }); pools.push(pool); // SubPool configuration Pool memory subPool = Pool({ level: uint8(2), maxNumber: uint256(1000), maxMember: uint256(100), number: uint256(1), last: uint256(subPoolId), share: uint256(50) }); pools.push(subPool); // set comission to 0 nfts[0].value = uint256(0); } }
if something wrong w/ level add to tokens
distribution[3] = distribution[3] + nfts[id].value;
14,049,220
[ 1, 430, 5943, 7194, 341, 19, 1801, 527, 358, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 7006, 63, 23, 65, 273, 7006, 63, 23, 65, 397, 290, 1222, 87, 63, 350, 8009, 1132, 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 ]
./partial_match/3/0x3F78bC772caac55f3E41d2c7c44feCEC2B80850F/sources/Asset.sol
* @dev Frozen account. @param _target The address to being frozen. @param _flag The status of the frozen/
function setFrozen(address _target,bool _flag) onlyAdmin public { frozen[_target]=_flag; emit FrozenStatus(_target,_flag); }
5,082,119
[ 1, 42, 9808, 2236, 18, 225, 389, 3299, 1021, 1758, 358, 3832, 12810, 18, 225, 389, 6420, 1021, 1267, 434, 326, 12810, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24340, 9808, 12, 2867, 389, 3299, 16, 6430, 389, 6420, 13, 1338, 4446, 1071, 288, 203, 3639, 12810, 63, 67, 3299, 65, 33, 67, 6420, 31, 203, 3639, 3626, 478, 9808, 1482, 24899, 3299, 16, 67, 6420, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-10 */ // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; abstract contract IGem { function dec() virtual public returns (uint); function gem() virtual public returns (IGem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IJoin { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (IGem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract IManager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // 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 div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, 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, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } /// @title A stateful contract that holds and can change owner/admin contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } /// @title AdminAuth Handles owner/admin privileges over smart contracts contract AdminAuth { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } /// @title Stores all the important DFS addresses and can be changed (timelock) contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } /// @title Implements Action interface and common helpers for passing inputs abstract contract ActionBase is AdminAuth { address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } /// @title Open a new Maker vault contract McdOpen is ActionBase { /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { (address joinAddr, address mcdManager) = parseInputs(_callData); joinAddr = _parseParamAddr(joinAddr, _paramMapping[0], _subData, _returnValues); uint256 newVaultId = _mcdOpen(joinAddr, mcdManager); return bytes32(newVaultId); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable override { (address joinAddr, address mcdManager) = parseInputs(_callData); _mcdOpen(joinAddr, mcdManager); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Opens up an empty vault /// @param _joinAddr Join address of the maker collateral /// @param _mcdManager The manager address we are using function _mcdOpen(address _joinAddr, address _mcdManager) internal returns (uint256 vaultId) { bytes32 ilk = IJoin(_joinAddr).ilk(); vaultId = IManager(_mcdManager).open(ilk, address(this)); logger.Log( address(this), msg.sender, "McdOpen", abi.encode(vaultId, _joinAddr, _mcdManager) ); } function parseInputs(bytes[] memory _callData) internal pure returns (address joinAddr, address mcdManager) { joinAddr = abi.decode(_callData[0], (address)); mcdManager = abi.decode(_callData[1], (address)); } }
@title Open a new Maker vault
contract McdOpen is ActionBase { function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { (address joinAddr, address mcdManager) = parseInputs(_callData); joinAddr = _parseParamAddr(joinAddr, _paramMapping[0], _subData, _returnValues); uint256 newVaultId = _mcdOpen(joinAddr, mcdManager); return bytes32(newVaultId); } function executeActionDirect(bytes[] memory _callData) public payable override { (address joinAddr, address mcdManager) = parseInputs(_callData); _mcdOpen(joinAddr, mcdManager); } function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } function _mcdOpen(address _joinAddr, address _mcdManager) internal returns (uint256 vaultId) { bytes32 ilk = IJoin(_joinAddr).ilk(); vaultId = IManager(_mcdManager).open(ilk, address(this)); logger.Log( address(this), msg.sender, "McdOpen", abi.encode(vaultId, _joinAddr, _mcdManager) ); } function parseInputs(bytes[] memory _callData) internal pure returns (address joinAddr, address mcdManager) { joinAddr = abi.decode(_callData[0], (address)); mcdManager = abi.decode(_callData[1], (address)); } }
2,285,148
[ 1, 3678, 279, 394, 490, 6388, 9229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 490, 4315, 3678, 353, 4382, 2171, 288, 203, 565, 445, 1836, 1803, 12, 203, 3639, 1731, 8526, 3778, 389, 1991, 751, 16, 203, 3639, 1731, 8526, 3778, 389, 1717, 751, 16, 203, 3639, 2254, 28, 8526, 3778, 389, 891, 3233, 16, 203, 3639, 1731, 1578, 8526, 3778, 389, 2463, 1972, 203, 565, 262, 1071, 8843, 429, 5024, 3849, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 261, 2867, 1233, 3178, 16, 1758, 312, 4315, 1318, 13, 273, 1109, 10059, 24899, 1991, 751, 1769, 203, 203, 3639, 1233, 3178, 273, 389, 2670, 786, 3178, 12, 5701, 3178, 16, 389, 891, 3233, 63, 20, 6487, 389, 1717, 751, 16, 389, 2463, 1972, 1769, 203, 203, 3639, 2254, 5034, 394, 12003, 548, 273, 389, 81, 4315, 3678, 12, 5701, 3178, 16, 312, 4315, 1318, 1769, 203, 203, 3639, 327, 1731, 1578, 12, 2704, 12003, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 1836, 1803, 5368, 12, 3890, 8526, 3778, 389, 1991, 751, 13, 1071, 8843, 429, 3849, 288, 203, 3639, 261, 2867, 1233, 3178, 16, 1758, 312, 4315, 1318, 13, 273, 1109, 10059, 24899, 1991, 751, 1769, 203, 203, 3639, 389, 81, 4315, 3678, 12, 5701, 3178, 16, 312, 4315, 1318, 1769, 203, 565, 289, 203, 203, 565, 445, 1301, 559, 1435, 1071, 16618, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 2254, 28, 12, 26995, 18, 882, 18264, 67, 12249, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 389, 81, 4315, 3678, 12, 2867, 389, 5701, 3178, 16, 1758, 389, 2 ]
// ALPHA 0.1.0 General Purpose Profit Splitter // INSERT ANYTHING ABOVE 1 FINNEY TO BE A CONTRIBUTOR. // TO INSERT PROFIT, SEND 1 FINNEY TO THIS CONTRACT FIRST! // THEN YOU HAVE TO SEND THE PROFIT DIRECTLY AFTER - IN 1 TRANSACTION - WITH THE SAME ADDRESS! // NO COPYRIGHT, NO FEES, NO OWNER (Only an owner in beta) // COPY THIS CODE ALL YOU WANT (not my responsibility) // IF YOU'RE INEXPERIENCED IN CODING, BUT WILLING TO LEARN. I'LL TRY TO DESCRIBE EVERYTHING THE BEST I CAN! // I'M AN INEXPERIENCED CODER MYSELF. // YOU CAN TELL, BECAUSE I HAVE NO IDEA HOW VERSION NUMBERS WORK. contract GeneralPurposeProfitSplitter { // Title of the contract, you have to give it a name. struct Contributor { // this will make a database of contributors, the address, contribution and profits are saved. address addr; // this is the contributors address uint index; // where does the contributor stand in the database index? uint contribution; // how much the contributor has contributed in the contract uint profit; // how much profit the contributor has made, because of the contribution uint total; // how much does this contributor have in total? uint lastContribution; // how much did the contributor contribute last time? uint lastProfit; // how much was the last profit amount? uint lastProfitShare; // how much share did the contributor have last time profit was distrebuted? uint lastPayout; // how much did the contributor pay out the last time? string error; // If there is something wrong you will know } Contributor[] public contributors; // use contributors[index of contributor].addr/contribution/profit. to get data from that contributor. uint contributorFound = 0; // if a contributor is found this value turns into an index number later on uint contributorTotal = 0; // this is a contributors contribution + profits uint contributorShare = 0; // this is how much that total is in comparison with all contributions uint public contributorsIndex = 0; // this counts how many contributors are in the contract. uint public totalContributorsContribution = 0; // this counts how much contribution in total is in the contract. uint public totalContributorsProfit = 0; // this counts how much profits in total is still in the contract. uint totalContributorsTotal = 0; // counts up all the contribution and all the profits now in contract. address public beta; // Only ME can decide to give all the contributions and profit back to the contributors. LAST RESORT or SCHEDULED! address public nextInputProfit; // IF you inserted 1 finney in the contract first, THEN that address will be saved for the next contract execution. uint i = 0; // the i gets used to find a contributor for certain functions uint correctProfit = 0; // Because i take 1 finney away for recognition, I will have to add one later. function GeneralPurposeProfitSplitter() { // without this, mist browser doesn't know how to deploy this contract, as far as I know beta = msg.sender; // I am the beta-address so I can give ether back if everything goes wrong } // ADD two lines of code empty between functions. I don't know why, but I read it somewhere that you have to. function() { // this function has no name, which means that this function will get triggered when only money gets send if (msg.value < 1 finney) { // DON'T SEND SOMETHING LESS THEN 1 FINNEY TO THIS CONTRACT msg.sender.send(msg.value); // well you can, but this contract will just send it back, all the wasted gas throw; // and we will pretend it never happened } if (msg.value == 1 finney) { // IF the value you send to this contract is 1 finney nextInputProfit = msg.sender; // THEN the address will get saved as nextInputProfit, because the next input will be profit throw; // THEN THE OTHER CONTRACT that provides the profit HAS to send the profit to this contract WITH THE SAME ADDRESS } if (nextInputProfit == msg.sender) { // IF this is the second time the smartcontract that provides profit insert ether, it checks its address to see if it matches nextInputProfit = 0; // this resets the nextInputProfit to nothing. because the code is now being executed and won't be executed again, unless it sends 1 finney again. correctProfit = msg.value + 1 finney; // this adds the 1 finney that was taken away for code recognition. insertProfitHere(); // GO TO the function that destributes profits. } else { // IF you're NOT a profit providing smartcontract and have NOT inserted 1 finney first, then the contract recognizes you as contributor for(i; i<contributors.length; i++) {// this will go through ALL contributors untill it has found a matching address (LEARN ABOUT FOR LOOPS ON GOOGLE (if it still exists)) if (contributors[i].addr == msg.sender) {// If it has found one, it'll prevent the same contributor added twice contributorFound = i; // then the number i is the contributors index number. i = contributors.length; // this will make the for loop stop, to save gas. } } i = 0; // resets that i thingy back to zero, because... you know. if (contributorFound > 0) { // if the contributorsFound is NOT 0, like in the beginning of this contract, that means this is not the first time this address contributed contributors[contributorFound].contribution += msg.value; // add the new contribution value to the existing contribution value contributors[contributorFound].total = contributorTotal; // for show in Mist Browser contributors[contributorFound].lastContribution = msg.value; // for show in Mist Browser contributorTotal = contributors[contributorFound].contribution + contributors[contributorFound].profit; // Counts up the total amount a contributor has } else { // if this is the first time your address contributed here, welcome first of all, and you will be added in the database contributors[contributorsIndex].addr = msg.sender; // IF you're the first contributor, you will get contributorsIndex number 0. contributors[contributorsIndex].index = contributorsIndex; // so you know where you stand contributors[contributorsIndex].contribution = msg.value; // your value will now be seen as a contribution, and you will receive profits contributors[contributorsIndex].total = msg.value; // for show in Mist Browser contributors[contributorsIndex].lastContribution = msg.value; // for show in Mist Browser contributorsIndex += 1; // add one to the contributors index, no two contributors gets the same index number } totalContributorsContribution += msg.value; // If you want to give you're contributors the correct share of profits, the total contributors amount has to be correct all the time. } } function insertProfitHere() { // so if the contract recognizes your input as profit, it executes this function. You can also use the mist browser to add profits. totalContributorsTotal = totalContributorsProfit + totalContributorsContribution; // count up everything to calculate shares later on i = contributors.length; // I begin with the last contributor, because last added, first served. uint CorrectProfitCounter = correctProfit; // I need an additional counter to NOT give out too much profit then that there is. uint addedProfit; //after calculating shares, addedProfit is the amount one contributor gets. uint errorBelow = 0; // in case there is not enought profit to share around, if it happens, something went wrong. for(i; i >= 0; i--) { // this gathers all the contributors one by one, starting with the last contributor contributorTotal = contributors[i].contribution + contributors[i].profit; // Counts up the total amount a contributor has contributorShare = contributorTotal / totalContributorsTotal; // compares it with the amount of all contribution addedProfit = contributorShare / correctProfit; // the contract gives the contributor the fair share in comparison of the rest of all the contributors CorrectProfitCounter -= addedProfit;// I don't want the contract balance to be below zero, because of miscalculations, so I keep subtracting to check if (CorrectProfitCounter > 0){ // if there is still enough profit to share, share it. If it doesn't, then something went wrong. contributors[i].profit += addedProfit; // add the profit to the contributors database index totalContributorsProfit += addedProfit; // also add that same amount to the total of all contributors contributors[i].lastProfit = addedProfit; // Also for show in the Mist browser } else { // if this code gets executes, then something went wrong and the duped ones get notified errorBelow = i; // let's hope this never happens i = 0; // this makes the for loop stop } } if (errorBelow >= 0){ // something went wrong, we have to tell the duped about it quick! for(errorBelow; errorBelow > 0; errorBelow--) { // for loop to tell the ones who are duped that something went wrong contributors[errorBelow].error = "Please cash all out and recontribute to continue getting profit"; // haha quickfix } } } function cashOutProfit() { // This is the best part for contributors for(i; i<contributors.length; i++) { // for loop again to search you up if (contributors[i].addr == msg.sender) { // see if it matches contributorFound = i; // we found you i = contributors.length; // stop the for loop msg.sender.send(contributors[contributorFound].profit); // send the profits you've earned totalContributorsProfit -= contributors[contributorFound].profit; // remove the profits from the total to correctly calculate shares in the future contributors[contributorFound].profit = 0; // if you've cashed all your profit out, you have no more profit in the contract } } i = 0; // this might be unnessecary, but who cares } function cashAllOut() { // this is when you want to stop getting profits as well for(i; i<contributors.length; i++) { // for loop to search you up if (contributors[i].addr == msg.sender) { // match or no? contributorFound = i; // tadaaaa i = contributors.length; // stop the for loop please contributorTotal = contributors[contributorFound].contribution + contributors[contributorFound].profit; // count all your funds up msg.sender.send(contributorTotal); // and send it back to you, have fun totalContributorsContribution -= contributors[contributorFound].contribution; // to correct shares later contributors[contributorFound].contribution = 0; // all gone, because you cashed out totalContributorsProfit -= contributors[contributorFound].profit; // to correct the shares later also contributors[contributorFound].profit = 0; // no profit if you've asked for it } } i = 0; // This is the end I guess } //------------------------------------------------------------------------------ //------ALPHA/BETA FUNCTIONS ONLY----------------------------------------------- //------------------------------------------------------------------------------ function giveAllBack() { // TIME TO YELL SCAM! if (beta == msg.sender) { // checks if the address executing this function is also the owner, to be sure for(i; i<contributors.length; i++) {// ow nevermind.. contributorTotal = contributors[i].contribution + contributors[i].profit; // count up how much the contributors have individually contributors[i].addr.send(contributorTotal); // aaaand send it back contributors[i].contribution = 0; // reset all the balances totalContributorsContribution = 0; // balance reset contributors[i].profit = 0; // never had a reset to serious totalContributorsProfit = 0; // balance reset } i = 0; // search function stuff } } function giveContributionsBackProfitBugged() { // Yeah now you can yell scam! if (beta == msg.sender) { // checks if the address executing this function is also the owner, or else everyone can do this for(i; i<contributors.length; i++) { // get all the contributors contributorTotal = contributors[i].contribution; // only give back all user contribution contributors[i].contribution = 0; // reset everything contributors[i].addr.send(contributorTotal); // Yeah so the contract now only has claimable profits left } i = 0; // at least I tried making this smartcontract } } function Fokitol() { // scream scam NOW!! If you don't, people will be baited and the world as we know it will end!! if (beta == msg.sender) { // is it the deployer? beta.send(this.balance); // send him everything, which is super lame to do if there are other people contributing as well. } } }
this is when you want to stop getting profits as well
function cashAllOut() {
12,905,336
[ 1, 2211, 353, 1347, 1846, 2545, 358, 2132, 8742, 9214, 1282, 487, 5492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 276, 961, 1595, 1182, 1435, 288, 8227, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]